I have a very simple UserControl with some borders and some decorations that react to mouseOver, pressed and some nice things.
I want to allow people to set the content of the text from outside, but when I set the content, the generated content presenter overwrites my whole WPF structure.
This is what I tried so far:
<UserControl tags tags tags>
<!-- This is the only way I found to style the textblock that WPF -->
<!-- generates to encapsulate the content string -->
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<TextBlock Background="Green"
HorizontalAligment="Center"
VerticalAlignment="Center"
Text = "{TemplateBinding Content}"/>
</ControlTemplate>
</UserControl.Template>
<!-- Here my borders and fancy things. I want to add animations -->
<!-- and react to mouseOver and Pressed like a button -->
<Border x:Name="SuperNiceBorder" tag tag tag>
<HERE I WANT THE CONTENTPRESENTER>
</Border>
</UserControl>
Is there a way to tell WPF I want the text set by the user in the Content just there ???
Move all your animations and triggers inside the ControlTemplate.
Replace your TextBlock with a ContentPresenter:
<UserControl x:Class="MySolution.MyControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Border x:Name="MyBorder" Background="Green">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
Content = "{TemplateBinding Content}"/></Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="MyBorder" Property="Background" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</UserControl.Template>
</UserControl>
And you can use the UserControl like these examples:
1:
<local:MyControl Content="Test Testing tester"/>
2:
<local:MyControl>
<TextBlock Text="Another test from a TextBlock"/>
</wpfAllPurposesTest:MyControl>