Markos
Markos

Reputation: 1633

WPF Setting both DataTemplate and ControlTemplate on a control does not work

I am obviously missing something very basic here. I have found similar questions but from none of the answers I was able to comprehend what I am doing wrong.

When I set ControlTemplate, my DataTemplate is not picked up.

I have created a very simple example of my problem:

<Window x:Class="WpfTesterProject.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfTesterProject"
        Title="Window1" Height="300" Width="300">

    <Window.Resources>
        <DataTemplate DataType="{x:Type local:Person}">
            <StackPanel>
                <TextBlock Text="{Binding FirstName}" />
                <TextBlock Text="{Binding LastName}" />
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

    <ContentControl Content="{Binding Content}">
        <ContentControl.Template>
            <ControlTemplate>
                <Border BorderBrush="Blue" BorderThickness="2">
                    <ContentPresenter />
                </Border>
            </ControlTemplate>
        </ContentControl.Template>
    </ContentControl>
</Window>

What I want to do is select user-defined data template loaded at runtime, but also I want to, for example, wrap every single element in border, no matter what the user template is or even if he did not specify any templates at all.

From what I have read from similar questions, I have to use <ContentPresenter /> in the ControlTemplate, but the result is the same as if I remove it - only border is shown.

Upvotes: 4

Views: 1636

Answers (1)

Bas
Bas

Reputation: 27105

I reproduced your application. It seems the problem is in the TargetType property of the ControlTemplate:

<ContentControl Content="{Binding}">
    <ContentControl.Template>
        <ControlTemplate TargetType="ContentControl">
            <Border BorderBrush="Blue" BorderThickness="2">
                <ContentPresenter />
            </Border>
        </ControlTemplate>
    </ContentControl.Template>
</ContentControl>

Upvotes: 6

Related Questions