I am having trouble implementing a ComboBox that reflects changes made to the underlying data source. Not an uncommon question from the number of posts I have read through so far, but I am still having trouble getting this to work. When a new record is added to the CaseFiles collection it doesn't appear in the drop down list until the application is restarted. What am I doing wrong?
All of the (EF) generated entities inherit from a BaseModel that implements INotifyPropertyChanged, and the ViewModel implements INotifyPropertyChanged as well through ViewModelBase.
The Combobox xaml looks like this:
<ComboBox x:Name="cbxSelect" Height="26" MinWidth="230"
ToolTip="DRE Number / Rolling Log Number / Operational File Number"
ItemsSource="{Binding CaseFiles}"
SelectedValue="{Binding SelectedCaseFile}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center" Foreground="DarkBlue" FontSize="14">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource NullToStringMultiConverter}">
<Binding Path="Evaluator.DreNumber"/>
<Binding Path="RollingLogNumber"/>
<Binding Path="FileNumber"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
ViewModel:
public class MainViewModel : ViewModelBase
{
private MyEntites db;
private ObservableCollection<CaseFile> caseFiles;
public ObservableCollection<CaseFile> CaseFiles
{
get { return caseFiles; }
}
public MainViewModel()
{
db = new MyEntities();
caseFiles = Convert<CaseFile>(db.CaseFile.GetAll().ToList())
}
public static ObservableCollection<T> Convert<T>(IEnumerable original)
{
return new ObservableCollection<T>(original.Cast<T>());
}
}
You are probably not adding the items to the same ObservableCollection instance that is returned by the CaseFiles property of your view model. Only when you add items to this very ObservableCollection instance a new item will appear in the ComboBox.
If you for example add an item to the db.CaseFile collection, this won't affect the ComboBox since it is bound to a completely different collection.
You are creating a brand new ObservableCollection once when your view model is constructed and after this there is no connection between this new collection and the List that you originally pass to the static Convert method.
So make sure that you only create a single instance of the MainViewModel class and that you are actually adding the items to its CaseFiles property and the DbContext.
Obviously you will need to provide a reproducible sample of your issue including any code snippets that show exactly how you actually add the items to the ObservableCollection if you need any further help on this. But provided that the DataContext of the ComboBox is set or bound to an instance of your MainViewModel, adding a CaseFile object to its CaseFiles property should update the ComboBox.