I’m working on a small WPF application in which I have a combobox that is bound to an ObservableCollection in the code behind:
public Molecule CurrentMolecule { get; set; }
public ObservableCollection<string> Formulas { get; set; }
public MainWindow()
{
CurrentMolecule = new Molecule();
Formulas = new ObservableCollection<string>(CurrentMolecule.FormulasList.ToList());
DataContext = this;
InitializeComponent();
}
<ComboBox x:Name="cmbFormula" ItemsSource="{Binding Path=Formulas}" SelectionChanged="cmbFormula_SelectionChanged"/>
This works fine to populate my combo box with the CurrentMolecule.FormulasList however if at some point I set CurrentMolecule to a new instance of Molecule the databinding no longer works. Do I need to implement some kind of OnPropertyChanged event so that no matter what the contents of the combo box will stay current with the CurrentMolecule.FormulasList?
You have to implement
INotifyPropertyChanged, only then the changes will be updated in UI.Here are the modifications that I’ve done to your code.
Edit:
A better approach is to create a ViewModel and then bind it to the DataContext of the
Window.Define a new class called
ViewModelas below. Note you might want to change the namespaceModify the
MainWindowcode behind file as below