How to Bind To Data within a Datatemplate of a ContentControl

非 Y 不嫁゛ 提交于 2019-11-29 00:37:49

问题


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.



来源:https://stackoverflow.com/questions/15389142/how-to-bind-to-data-within-a-datatemplate-of-a-contentcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!