Introduction
This article demonstrates how to use Property trigger with WPF UI controls and briefs little about Property Trigger. In this article we have covered example of both XAML and Behind code.
Getting Started
A Property Trigger gets executed when property of WPF UI control is changed. For example TextBlockForegroundcolor can be changes with the help of property trigger when IsMouseOverproperty is gets changed.
<Style TargetType="typ_of_control" x:Key="key_name_of_style">
<Style.Triggers>
<Trigger Property="Name_Of_Property" Value="value_Of_Property">
<Setter Property="PropertyName_Of_Target_Element" Value="Value_To_Be_Change"></Setter>
</Trigger>
</Style.Triggers>
</Style>
The Property Named 'Property' in trigger accepts the name of property of bound element (whose visual is going to change) that means the trigger will check the value of that property. The Value property of the trigger accepts the value, based whom trigger will execute that means trigger will be fired when property value of bound element matches the provided value .
The setters in trigger is collection of setter object, the setter object is actually changing the UI element vitality. The property named 'Property' accepts the value that is going to be changes based on the Value property of setter.
XAML Code Example
Declaration <Style TargetType="TextBlock" x:Key="tbktrigger">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Foreground" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
Use of Trigger <TextBlock Style="{StaticResource tbktrigger}" x:Name="textBlock" Text="Property Trigger Example"/>
Behind Code Example
This example demonstrates how to declare trigger using behind code in C# and use that style into controls. it also gives example how to use style for trigger when you declared in xaml. Style style = new Style();
style.TargetType = typeof(TextBlock);
Trigger trigger = new Trigger();
trigger.Property = TextBlock.IsMouseOverProperty;
trigger.Value = true;
Setter setter = new Setter();
setter.Property = TextBlock.ForegroundProperty;
setter.Value = Brushes.Red;
trigger.Setters.Add(setter);
style.Triggers.Add(trigger);
this.textBlock.Style =style;
When Style Declared in XAML and Use in Behind Code this.textBlock.Style = (Style)Application.Current.Resources["ListViewItemTextBlockStyle"];
Related Articles
Summary
In this article we demonstrate how to declare property trigger and how to use that in both xaml and behind code. Hope this demonstrator will make you helpful.
Thanks
Comments
Post a Comment