Triggers in WPF
WPF Triggers :
Trigger performs its work based on one or more conditions.
Types of triggers :
Property triggers—Invoked when the value of a dependency property changes
Data triggers—Invoked when the value of a plain .NET property changes
Event triggers—Invoked when a routed event is raised
Property Triggers :
Data Triggers :
Data triggers are just like property triggers, except that they can be triggered by any .NET property rather than just dependency properties.
Expressing More Complex Logic with Triggers
The logic expressed with the previous triggers has been in the form “when property=value, set the following properties.” But more powerful options exist:
. Multiple triggers can be applied to the same element (to get a logical OR).
. Multiple properties can be evaluated for the same trigger (to get a logical AND).
Dependency Property / Change Notification :
Dependency property depends on providers to determinse its value .
D.P. used with Data Binding, animation, Styles
Internally dependency Property is registered with DependencyProperty.Register method.
Whenever the value of a dependency property changes, WPF can automatically trigger a number of actions depending on the property’s metadata.
built-in change notification is done through property triggers, which enable you to perform your own custom actions when a property value changes.
Dependency without Property Trigger
<Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
MinWidth=”75” Margin=”10”>Help</Button>
<Button MouseEnter=”Button_MouseEnter” MouseLeave=”Button_MouseLeave”
MinWidth=”75” Margin=”10”>OK</Button>
Change the foreground to blue when the mouse enters the button
void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Blue;
}
void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button b = sender as Button;
if (b != null) b.Foreground = Brushes.Black;
}
Dependency with Property Trigger
With a property trigger, however, you can accomplish this same behavior purely in XAML.
<Button MinWidth=”75” Margin=”10”>
<Button.Style>
<Style TargetType=”{x:Type Button}”>
<Style.Triggers>
<Trigger Property=”IsMouseOver” Value=”True”>
<Setter Property=”Foreground” Value=”Blue”/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style> OK </Button>