I really tried to find the solution but I failed. So I have ResourceDictionary in separate xaml file and Control class in another cs file. Here is xaml code:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp1" x:Class="Control1">
<Style TargetType="{x:Type local:Control1}">
<Setter Property="GridColor" Value="Red"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:Control1}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid x:Name="PART_Grid" Background="{TemplateBinding GridColor}"
Height="{TemplateBinding Height}" Width="{TemplateBinding Width}"/>
<Button Grid.Column="1" x:Name ="PART_Button" Width="50" Height="50"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="GridColor" Value="Black"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
In cs file I change IsChecked
by OnMouseEnter
and OnMouseLeave
event handlers. It works fine. The problem is that when I change GridColor
in OnButtonClick
event handler for example, it changes, but after that the trigger setter doesn't work (but another setters still work fine). No exceptions, no messages in output. Did I miss something?
Here is cs code if somebody needs it
public class Control1: Control
{
public static readonly DependencyProperty GridColorProperty =
DependencyProperty.Register("GridColor", typeof(Brush), typeof(Control1), new PropertyMetadata(new SolidColorBrush(Colors.Red)));
public static readonly DependencyProperty IsCheckedProperty =
DependencyProperty.Register("IsChecked", typeof(bool), typeof(Control1), new PropertyMetadata(false));
public Brush GridColor
{
get { return (Brush)GetValue(GridColorProperty); }
set { SetValue(GridColorProperty, value); }
}
public bool IsChecked
{
get { return (bool)GetValue(IsCheckedProperty); }
set { SetValue(IsCheckedProperty, value); }
}
public override void OnApplyTemplate()
{
((Grid)GetTemplateChild("PART_Grid")).MouseEnter += Grid_MouseEnter;
((Grid)GetTemplateChild("PART_Grid")).MouseLeave += Grid_MouseLeave;
((Button)GetTemplateChild("PART_Button")).Click += Button_Click;
base.OnApplyTemplate();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
GridColor = new SolidColorBrush(Colors.DarkBlue);
}
private void Grid_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
IsChecked = false;
}
private void Grid_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
IsChecked = true;
}
}