How to Bind To Data within a Datatemplate of a ContentControl
Asked Answered
P

1

29

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?

Punster answered 13/3, 2013 at 15:11 Comment(0)
O
73

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.

Odum answered 13/3, 2013 at 15:18 Comment(2)
Do you have a link to the docs on this? It totally solved my problem but am curious if there are any other gotchas.Astrology
This link takes you to the ContentTemplate property of the Content control and here we can see that the ContentTemplate Gets or sets the data template used to display the content. learn.microsoft.com/en-us/dotnet/api/…. The content can be any object as per learn.microsoft.com/en-us/dotnet/api/…Winterize

© 2022 - 2024 — McMap. All rights reserved.