I start with WPF and bindings, but there is a weird behavior that I don't understand.
Example 1: A very simple form of WPF in which there is 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;
MessageBox.Show(this.c.SelectedItem.ToString());
}
Can you explain to me why this will happen because of this .c.SelectedItem will be NULL.
So I, though ... not a problem, because it is in the constructor, 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 ...
Note. If I delete the Messagebox object, then the binding work is fine, I have a value in the combo box. This is similar to the fact that after the datacontext is set, it will take some time. But how do you know when the binding will be done?
Tx for your help.