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?