Home > Binding, WPF > Gorgeously simple – part 1

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…

Bland? Yup. Powerful? Incredibly!

Advertisement
Categories: Binding, WPF Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.