How to Bind To Data within a Datatemplate of a Con

2019-02-02 04:00发布

问题:

I have the following simplified Example:

    <Window x:Class="TemplateBinding.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary
                            Source="pack://application:,,,/TemplateBinding;component/PersonTemplate.xaml" />
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
        </Window.Resources>
        <Grid>
            <ContentControl ContentTemplate="{StaticResource PersonTemplate}" />
        </Grid>
    </Window>

With:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

        <DataTemplate x:Key="PersonTemplate">
            <Border Width="100" Height="100" Background="RosyBrown">
                <TextBlock Text="{Binding Path=FirstName}" VerticalAlignment="Center" TextAlignment="Center"/>
            </Border>
        </DataTemplate>

    </ResourceDictionary>

as my DataTemplate in a separate ResourceDictionary file.

I set my DataContext in the Construcor of my MainWindow and have verified it by just displaying the first name like this: <ContentControl Grid.Row="1" Content="{Binding FirstName}"/>.

In an other scenario wher I use a DataTemplate with a ListBox I do the Binding exactly the same way in my DataTemplate and it just works.

I know that the DataTemplate is working except the binding because it correctly shows the size and background color.

What am I doing wrong? How would the Binding in my DataTemplate have to look?

回答1:

You need to bind the Content-Property of the ContentControl

<ContentControl Content="{Binding}" ContentTemplate="{StaticResource PersonTemplate}" />

This will set the DataContext of the ContentControl as Content of the control.

Setting only the ContentTemplate property is not enough. The ContentControl does not implicitly use its DataContext as Content.