Thursday, July 23, 2015

Behaviors and Trigger Action

Behaviors
Behavior introduced in Blend 3 (System.Windows.interactivity.dll). The main use of Behavior is to provide additional functionalities and extensibility to controls without writing code in the code-behind.

Create a class by inheriting from Behavior and override OnAttached and OnDetaching methods. In theOnAttached you can hook the event and in OnDetaching, you have to unhook the events hooked in theOnAttached. The action be done in event handler delegate.
class CheckBoxBehavior : Behavior<CheckBox>
{
   protected override void OnAttached()
   {
       this.AssociatedObject.Click += AssociatedObject_Click;
   }

   void AssociatedObject_Click(object sender, System.Windows.RoutedEventArgs e)
   {
       if (AssociatedObject.IsChecked == true)
           this.AssociatedObject.Foreground = Brushes.Green;
       else if (this.AssociatedObject.IsChecked == false)
           this.AssociatedObject.Foreground = Brushes.Red;
       else
           this.AssociatedObject.Foreground = Brushes.Black;
   }

   protected override void OnDetaching()
   {
       this.AssociatedObject.Click -= AssociatedObject_Click;
   }
}
And in XAML, the created behavior can be added to control through the Interaction.Behaviors attached property.

<CheckBox x:Name="Checkbox"
           Content="Behaviour"
           IsThreeState="True">
   <i:Interaction.Behaviors>
       <local:CheckBoxBehavior />
   </i:Interaction.Behaviors>
</CheckBox>


Trigger Action
This is same as Behavior. The only difference is the event cab be specified in XAML itself. It is not required to override OnAttached and OnDetaching. Ythod will be called when the particularou have to just override Invoke method. Invoke me event invoked. The event arguments will be passed as parameter to Invoke method override.

public class TriggerActionClick : TriggerAction<CheckBox>
{
   protected override void Invoke(object parameter)
   {
       if (AssociatedObject.IsChecked == true)
           this.AssociatedObject.Foreground = Brushes.Green;
       else if (this.AssociatedObject.IsChecked == false)
           this.AssociatedObject.Foreground = Brushes.Red;
       else
           this.AssociatedObject.Foreground = Brushes.Black;
   }
}
In XAML, specify the EventName through EventTrigger.

<CheckBox Content="TriggerAction" IsThreeState="True">
   <i:Interaction.Triggers>
       <i:EventTrigger EventName="Click">
           <local:TriggerActionClick />
       </i:EventTrigger>
   </i:Interaction.Triggers>
</CheckBox>

1 comment: