The Order Issue of XAML Attributes
When programming Silverlight, it is neccessary to pay attention to the order of the XAML element’s attributes. Here is a simple example.
Here is the ListBox in the XAML:
<ListBox SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding Items}" x:Name="listBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
and the the data binding in the code-behind:
public MainPage() { this.InitializeComponent(); this.listBox.DataContext = new Data(); } public class Data { public int[] Items { get { return new int[] { 0, 1, 2, 3 }; } } public int SelectedItem { get { return 2; } } }
We hope 4 items appear in this ListBox, and the third one is selected. But it won’t work as expected:
The third item is not selected because the SelectedItem attribute is binded before ItemsSource. So when SelectedItem is set, there is no ItemsSource to check.
The solution is to swap the two attributes, put ItemsSource before SelectedItem:
<ListBox ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}" x:Name="listBox">
Now the control works:
The conclusion is, the XAML attributes are order-sensitive. I am wondering whether this is by design…