Gorgeously simple – part 2
Remember how easy it is to display ‘something’ in WPF? Well, what if you’ve got a whole list of stuff? no probs…
1. Create a real simple DataTemplate, similar to last time…
<DataTemplate DataType="{x:Type local:Book}" x:Key="bookListItemTemplate">
<DockPanel>
<TextBlock DockPanel.Dock="Right" Width="60" Text="{Binding StringFormat={}{0:yyyy}, Path=FirstPublished}" />
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}, {1}">
<Binding Path="Title" />
<Binding Path="Author" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DockPanel>
</DataTemplate>
2. Set the DataContext to be a list of our stuff… anything that implements the IList interface will do… List<T> is the easiest for demonstration purposes (more on this later)
IList Books = new List<Book>
{
new Book
{
Author = "Orson Scott Card",
Title = "Ender's Game",
FirstPublished = new DateTime(1977, 08, 01),
Publisher = "Tor books"
},
new Book
{
Author = "Terry Pratchett",
Title = "Mort",
FirstPublished = new DateTime(1987, 01, 01),
Publisher = "Victor Gollancz"
},
new Book
{
Author = "Truman Capote",
Title = "In Cold Blood",
FirstPublished = new DateTime(1966, 01, 01),
Publisher = "Random House"
}
};
this.DataContext = Books;
3. Throw the list onto the View in an items presenter…
<ListBox
ItemsSource="{Binding}" ItemTemplate="{StaticResource bookListItemTemplate}"
HorizontalContentAlignment="Stretch" />
Seriously, what could be simpler? Isn’t WPF stunning? notice how I have deliberately not introduced glimmering shadow effects or animations to spin the controls into place? WPF is not (only) ‘eye-candy’… the aesthetic beauty comes from the delicious simplicity with which we can generate ultra-powerful user interfaces, in order to deliver pleasurable user-experiences…
I just love it
