How to create and use Actions in WPF

Hi, today I’m going to show how can you create and use actions in WPF which are similar to behaviors described in my previous post.

Single action represents a piece of functionality that can be attached to any element in UI tree. The main difference between actions and behaviors is that user of particular action can decide what kind of event or data change invokes it whereas behavior encapsulates this decision.

For instance this can be action which shows message box or action that changes background property of element it is attached to whenever some property changes or event occurs.

Let me show how actions can be created:

public class ChangeForegroundAction : TriggerAction<TextBox> { public Color Color { get; set; } protected override void Invoke(object parameter) { AssociatedObject.Foreground = new SolidColorBrush(Color); } }

Here is code that uses this action to invoke it when mouse is either over TextBox or not:

TextBox Name="txt" Width="60" Height="30"> <i:Interaction.Triggers> <ei:DataTrigger Binding="{Binding IsMouseOver, ElementName=txt}" Value="True"> <ActionsSample:ChangeForegroundAction Color="Red"/> </ei:DataTrigger> <ei:DataTrigger Binding="{Binding IsMouseOver, ElementName=txt}" Value="False"> <ActionsSample:ChangeForegroundAction Color="Black"/> </ei:DataTrigger> </i:Interaction.Triggers> </TextBox>

As you can see, code declares what causes this action to be executed and if you run this sample, you will have TextBox with varying foreground.

I created this action only for example and of course in real world development you would have more complex actions instead.

BTW, you can use actions provided in Microsoft.Expression.Interactions.dll assembly like ChangePropertyAction or CallMethodAction etc.

If you have any questions don’t hesitate to ask me. Bye Winking smile