Recall my previous post, I’ve talked about how to implement custom Actions. In this post I would like to explain how to implement custom Triggers.
As you may already know, trigger is the cause and action is the effect of that cause.
The question is, why would you like to implement a custom trigger?
So lets start with a little example: Blend 3 comes with only event triggers. But what if you want to invoke an action when property changes?
For that reason you would like to implement a custom trigger. This custom trigger will have a property name as an input, and from that moment it will listen to that property change notification.
Implementing a custom trigger is easy as deriving from the TriggerBase<T> base class, overriding the OnAttached/OnDetached methods accordantly for defining the trigger behavior.
In our case, we are overriding the OnAttached method to extract the relevant property, and then to register its value change. In the value change event handler, we are calling the InvokeActions base method for activating associated actions.
public class PropertyTrigger : TriggerBase<DependencyObject>
{
private DependencyPropertyDescriptor _propertyDescriptor;
protected override void OnAttached()
{
base.OnAttached();
if (Property == null)
{
return;
}
// Get the property type descriptor and register to value change
}
protected override void OnDetaching()
{
base.OnDetaching();
// Unregister from value change
}
private void ValueChanged(object sender, EventArgs args)
{
// Call InvokeActions here
}
#region Property
public string Property
{
get { ... }
set { ... }
}
...
}
To use this custom trigger, you should drop an action, go to the action properties, select New on TriggerType and pick the PropertyTrigger.
Now that we can create custom triggers, we can have more triggers in our actions toolbox, simplifying the design phase and make the UI designer happy :-)
You may download the full code from here.
In my next post I’ll talk about implementing custom behaviors, so stay tuned.