Reputation: 100
I'm trying to get the IsMouseOver trigger working for datatemplate. For some reason it is not firing. I also tried the http://www.wpfmentor.com/2009/01/how-to-debug-triggers-using-trigger.html but I do not see anything in the trace. Here is the code:
XAML:
<Window x:Class="FirstSImpleDataApp.Window4"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window4" Height="300" Width="300">
<Window.Resources>
<ResourceDictionary>
<DataTemplate x:Key="tmptemplate">
<Border x:Name="brd" BorderBrush="Black" BorderThickness="2">
<TextBlock x:Name="txt">my text box</TextBlock>
</Border>
<DataTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="txt" Property="Background" Value="Red"></Setter>
<Setter TargetName="txt" Property="Foreground" Value="Green"></Setter>
<Setter TargetName="brd" Property="Background" Value="Green"></Setter>
</Trigger>
</DataTemplate.Triggers>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Canvas x:Name="can" Loaded="can_Loaded">
</Canvas>
</Window>
Code behind:
public partial class Window4 : Window
{
public Window4()
{
InitializeComponent();
}
private void can_Loaded(object sender, RoutedEventArgs e)
{
var tmp = this.TryFindResource("tmptemplate") as DataTemplate;
var obj = (FrameworkElement)tmp.LoadContent();
can.Children.Add(obj);
}
}
Any help is appreciated!
Upvotes: 1
Views: 1305
Reputation: 25623
Your triggers actually work just fine. The problem is with how you're instantiating the template and adding it to your Canvas
programmatically.
Apply the template directly in your Xaml to see it work:
<Canvas x:Name="can">
<ContentControl ContentTemplate="{StaticResource tmptemplate}" />
</Canvas>
If you want to apply it programmatically, apply the template to a ContentControl
or ContentPresenter
and drop it in the Canvas
instead:
private void can_Loaded(object sender, RoutedEventArgs e)
{
var tmp = this.TryFindResource("tmptemplate") as DataTemplate;
can.Children.Add(new ContentPresenter { ContentTemplate = tmp });
}
Upvotes: 1
Reputation: 545
Here is an alternative using Style triggers. The border remains black, but with a green margin from the TextBlock.
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
<Setter Property="Foreground" Value="Green"/>
<Setter Property="Margin" Value="2"/>
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Green"/>
</Trigger>
</Style.Triggers>
</Style>
<Border BorderThickness="1" BorderBrush="Black">
<TextBlock Text="My Text Block"/>
</Border>
Upvotes: 0