I am new to using the ControlTemplate
. I am writing my first control but I am having (what seems to me) a very strange issue.
Any dependency properties that I make TemplateBinding
to work, but any properties from the .NET framework objects i.e. the Content
property of a ContentControl
or the Items
property of an ItemsControl
does not get populated at runtime.
I am sure I am missing something... Just what it is I dont know...
An example of the code is below:
The class is very simple at the moment:
public class Title : ContentControl
{
}
And the Template is:
<Style TargetType="{x:Type UI:Title}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UI:Title}">
<TextBlock Text="{TemplateBinding Content}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The base ContentControl
class is the .NET class located in the System.Windows.Controls.Control namespace.
Thanks,
Adam
I believe if you'd like to override where the Content is placed you can do that using a ContentPresenter.
<Style TargetType="{x:Type UI:Title}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UI:Title}">
<Label>
<ContentPresenter />
</Label>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Note I've also changed from a TextBlock to a Label as I believe the TextBlock.Text property will not accept everything from ContentControl.Content. Here is an example I put together that works as intended:
<Window x:Class="ContentControlTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ContentControlTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type local:Title}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Title}">
<Button>
<ContentPresenter />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<local:Title>
<TextBlock Text="Happy Days!" />
</local:Title>
</Window>