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.
It is because the selectionchanged has not triggered yet so selecteditem is still null.
private void c_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(this.c.SelectedItem.ToString());
}
If you are new to WPF I suggest you go and have a look at the MVVM pattern. There is a really nice introduction video here: http://blog.lab49.com/archives/2650
Your binding happens during the Window_Loaded event but it's not drawn to scren so there isn't a SelectedItem yet.
You will have to listen to the PropertyChanged event of your Binding or DataContext or whatever. Then OnPropertyChanged, bring up your messagebox
Tx for the comment, it should be something like this, I try this, and this is working :
BindingClass ToBind = new BindingClass();
public Window1()
{
InitializeComponent();
ToBind.MyCollection = new List<string>() { "1", "2", "3" };
this.DataContext = ToBind;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show(this.c.SelectedItem.ToString());
}
So here, even if it is not drawn on the screen the selecteditem is already fetched ... very strange.
精彩评论