Gorgeously simple – part 1
Adding a ‘thing’ to a View in WPF is deliciously simple…
Step 1.
Define your thing
public class Book
{
public string Title { get; set; }
public string Author { get; set; }
public DateTime FirstPublished { get; set; }
public string Publisher { get; set; }
}
Step 2.
Define the WPF template for presenting this thing to the world…
<DataTemplate DataType="{x:Type local:Book}" x:Key="bookTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Text="Title" />
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Title}" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="Author" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Author}" />
<TextBlock Grid.Row="2" Grid.Column="0" Text="Published" />
<TextBlock Grid.Row="2" Grid.Column="1">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} ({1:MMM yyyy})">
<Binding Path="Publisher" />
<Binding Path="FirstPublished" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
</DataTemplate>
Step 3.
Set the DataContext of your view to be an instance of your thing…
public Window1()
{
InitializeComponent();
this.DataContext = new Book
{
Author = "Orson Scott Card",
Title = "Ender's Game",
FirstPublished = new DateTime(1977, 08, 01),
Publisher = "Tor books"
};
}
Step 4.
Just chuck your thing on the screen…
<ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource bookTemplate}" />
Content="{Binding}" means just use the object set as the DataContext, and ContentTemplate="{StaticResource bookTemplate}" means use the template called ‘bookTemplate’ to render the thing…
and you see…
Advertisement
Categories: Binding, WPF
Binding, DataTemplate, WPF
