microsoft/XamlBehaviorsWpf

Interaction.Triggers doesn't work in ControlTemplate

ihsansfd opened this issue · 1 comments

Describe the bug
The trigger works well inside a Control or some other Dependency Object inherited object. But I tried to use it inside ControlTemplate but the compiler throws me this exception: "ArgumentException: Object of type 'System.Windows.Controls.ControlTemplate' cannot be converted to type 'System.Windows.DependencyObject'." Also the XAML runtime gives me this: "The attached property "Triggers" can only be applied to types that are derived from Dependency Object".

What is the workaround for this? I think it's important to have the trigger functionality work inside the ControlTemplate, as in my case I need to define a trigger for a property that is specific to the control being templated.

To Reproduce
Define the Interaction.Triggers inside the ControlTemplate of a control.

My example:
<Style TargetType="ToggleButton" x:Key="ToggleButtonStyle"> <Setter Property="Width" Value="50"/> <Setter Property="Height" Value="20"/> <Setter Property="FontSize" Value="15"/> <Setter Property="Cursor" Value="Hand"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ToggleButton"> <behaviors:Interaction.Triggers> <behaviors:EventTrigger EventName="Checked"> <behaviors:ChangePropertyAction PropertyName="Margin" TargetName="PART_Toggler" Value="32,0,0,0"/> </behaviors:EventTrigger> <behaviors:EventTrigger EventName="Unchecked"> <behaviors:ChangePropertyAction PropertyName="Margin" TargetName="PART_Toggler" Value="3,0,0,0"/> </behaviors:EventTrigger> </behaviors:Interaction.Triggers> <ControlTemplate.Resources> <SolidColorBrush x:Key="HoverBrush" Color="{Binding Source={StaticResource MainHoverColor}, Path=Color}"/> <SolidColorBrush x:Key="BorderBackground" Color="{Binding Source={StaticResource TogglerBackground}, Path=Color}"/> </ControlTemplate.Resources> <Border x:Name="PART_Border" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Tag="{TemplateBinding Tag}" CornerRadius="10"> <Border.Background> <SolidColorBrush Color="{Binding Source={StaticResource BorderBackground}, Path=Color}"/> </Border.Background> <Button x:Name="PART_Toggler" HorizontalAlignment="Left" Width="{TemplateBinding FontSize}" Height="{TemplateBinding FontSize}" IsHitTestVisible="False" Margin="3 0 0 0"> <Button.Template> <ControlTemplate> <Ellipse Fill="White"/> </ControlTemplate> </Button.Template> </Button> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style>

Expected behavior
I expect the EventTriggers also works inside the ControlTemplate.

Desktop (please complete the following information):

  • Version with bug: 1.1.39

As indicated by the error message you were given, this is by design.

For this specific scenario you should use the ControlTemplate.Triggers property