I'm beginning with WPF and binding, but there are some strange behavior that I don't understand.
Exemple 1 : A very simple WPF form, with only one combobox (name = C) and the following code in the constructor :
public Window1()
{
InitializeComponent();
BindingClass ToBind = new BindingClass();
ToBind.MyCollection = new List<string>() { "1", "2", "3" };
this.DataContext = ToBind;
//c is the name of a combobox with the following code :
//<ComboBox Name="c" SelectedIndex="0" ItemsSource="{Binding Path=MyCollection}" />
MessageBox.Show(this.c.SelectedItem.ToString());
}
Can you explain me why this will crash because of this.c.SelectedItem being NULL.
So I though ... no problem it's because it's in the constructor, let's put the code in the Loaded form event :
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
BindingClass ToBind = new BindingClass();
ToBind.MyCollection = new List<string>() { "1", "2", "3" };
this.DataContext = ToBind;
MessageBox.Show(this.c.SelectedItem.ToString());
}
Same problem this.c.SelectedItem is null...
Remark : If I remove the Messagebox thing, then the binding work fine, I have the value in the combobox. It's like if "some" time was needed after the datacontext is set. But how to know when the binding will be done ?
Tx you for your help.