0

I am trying to bind an ÒbservableCollection to a ComboBox using MVVM.

Here is the model:

 public class ItemModel
    {
        public string Name{ get; set; }
    }

ViewModel:

public class ItemsViewModel : INotifyPropertyChanged
{
    public ObservableCollection<ItemModel> ObsItems{ get; set; }
    public ItemsViewModel ()
    {       
        List<string> items=MyDataTable.AsEnumerable().Select(row => row.Field<string>
        ("Id")).Distinct().ToList();

        ObsItems= new ObservableCollection<ItemModel>();

        foreach (var item in items)
        {
            ObsItems.Add(
                new ItemModel
                {
                    Name = item
                }
                );
        }

    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void RaisePropertyChanged(string propertyName)
    {
        if (this.PropertyChanged != null)
        {
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

View:

<ComboBox HorizontalAlignment="Left" Margin="65,85,0,0" VerticalAlignment="Top" Width="120" 
ItemsSource="{Binding ObsItems}">
                <ComboBox.DataContext>
                    <Models:ItemsViewModel />
                </ComboBox.DataContext>
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}"/>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

This code does not work when building from scratch. But it works during run time, when the view code (xaml) is modified. It stops working once the program is exited and is run again. What am I missing out?

Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/220968/discussion-on-question-by-rahul-sureshbabu-binding-an-observable-collection-to-c). – Samuel Liew Sep 04 '20 at 10:09

1 Answers1

1

You should use a readonly ObservableCollection property:

public class ItemsViewModel
{
    public ObservableCollection<ItemModel> Items { get; } 
        = new ObservableCollection<ItemModel>();

    public void InitializeItems()
    {
        Items.Clear();

        foreach (var item in MyDataTable
            .AsEnumerable()
            .Select(row => row.Field<string>("Id"))
            .Distinct()
            .Select(name => new ItemModel { Name = name }))
        {
            Items.Add(item);
        }
    }
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Please see the updated ViewModel. The original issue still exists. Why do you think the data appears when commenting and uncommenting the ComboBox DataContext? Is this not the proper way to set the data context? Thanks. – Rahul Sureshbabu Sep 04 '20 at 08:52