I am trying to understand Binding so I have come up with a very simple program to try and test it.
I have the following element in my MainWindow:
<ComboBox Name="comboBox1" ItemsSource="{Binding}" />
In my Code I have the following observable collection:
public ObservableCollection<string> ComboItems = new ObservableCollection<string>();
I can successfully add items this way at any point during runtime:
comboBox1.DataContext = ComboItems;
ComboItems.Clea();
ComboItems.Add("Item");
My question is, how could I set the DataContext in XAML so that I don’t have to do it in code? Is it possible?
Thank you!
Something common is:
However usually you want to inject another object instance as
DataContext, have a look at the MVVM pattern for example. Properties in WPF are inherited, so theComboBoxhas theDataContextof theWindow, it can be overwritten at any level though.Note: For the Binding to work
ComboItemsneeds to be a public property, not a field.Resources of interest: