Gorgeously simple – part 3
To wrap up this brief series of demonstrations, I’m just going to glue the previous two posts together to show you something that made me go ‘wow’
We’ve looked at how to display an object, and how to display a list of objects on a window using a DataTemplate and some simple DataBinding.
Put these two concepts together, mix it up with WPF’s ‘Current Item’ functionality and what have you got? A super-simple Master-Detail page…
1. Using the DataTemplates defined in the previous posts, split the Window’s main grid into two; put the list on the left hand side, then the detail in the right
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<ListBox
Grid.Column="0"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}" ItemTemplate="{StaticResource bookListItemTemplate}"
HorizontalContentAlignment="Stretch" />
<ContentPresenter
Grid.Column="1" Margin="4"
Content="{Binding}" ContentTemplate="{StaticResource bookTemplate}" />
</Grid>
2. Remark upon how Robert is your Father’s Brother… It truly is that easy.
So how do you refresh the ContentPresenter with the data from the selected item from the list on the left-hand side? You absolutely don’t need to… Synchronising the ‘current item’ with the ListBox does all the work for you… cool eh?
One last thing: Notice how we’ve bound the ItemsSource to the DataContext of the ListBox (and, by extension since the DataContext is not explicitly set, the DataContext of the Window)? This is (from the previous post) a list of books, which appears in the list box exactly as one would expect.
Now notice how we have bound the Content of the ContentPresenter to exactly the same object (i.e. a list of books)? The ContentPresenter is smart enough to work out that it can only cope with one thing at a time, so it simply takes the current item out of the list and presents that…
Master-detail pages have never been so simple…
