In C# ASP.NET, setting properties of a control on event occurrence is done with C#(.cs) file which is called as back end code. But in Windows Presentation Foundation(WPF),we have a feasibility to set the properties of a control in XAML file itself without the use of C#(.cs) file.
Let us see the implementation of Button click event:
- A general Trigger to set a property when a property is changed is as follows:
<ControlTemplate.Triggers>
<Trigger Property="Background" Value="White">
<Setter Property="Foreground" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
<Trigger Property="Background" Value="White">
<Setter Property="Foreground" Value="Black" />
</Trigger>
</ControlTemplate.Triggers>
- Event Trigger(Which is desired and cannot be possible to implement)
<ControlTemplate.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<Setter Property="Foreground" Value="Black" />
</EventTrigger>
</ControlTemplate.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<Setter Property="Foreground" Value="Black" />
</EventTrigger>
</ControlTemplate.Triggers>
- But the above code cannot be implemented as the Event Triggers doesn't support Setter tags, Hence, we have another approach in Event Triggers to set any property of a control as follows:
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="ButtonGrid"
<BeginStoryboard>
<Storyboard>
<ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="ButtonGrid"
Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BlackBrush}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource BlackBrush}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>