02 May 2010

Always databind SelectedItem before ItemsSource

The order in which bindings are defined in Xaml are relevant. Look at this Example: I have a ComboBox and a ViewModel. The ItemsSource of the ComboBox is bound to the Repositories property and SelectedItem is bound to SelectedRepository.

<ComboBox ItemsSource="{Binding Repositories}"
          SelectedItem="{Binding SelectedRepository}" />

The constructor of the ViewModel initializes the Repositories with a non empty collection and sets the SelectedRepository to the first element.

public ViewModel()
{
    Repositories = new List<string> {"First", "Second", "Third"};
    SelectedRepository = Repositories[0];
}

Yet, immediately after starting, I got null reference exceptions from other databound properties that are referencing the SelectedRepository property! After a little debugging I found out that when assigning the ViewModel to the DataContext of the view, the Binding Engine assigns null to the SelectedRepository! If you change the declaration of Databinding everything works as expected:

<ComboBox SelectedItem="{SelectedRepository}"
          ItemsSource="Repositories" />
Conclusion: the order of databinding declaration matters!

No comments:

Post a Comment