Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding question

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.

like image 763
Fabian Avatar asked Dec 20 '25 00:12

Fabian


1 Answers

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

like image 85
Michael Avatar answered Dec 22 '25 20:12

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!