Click here to Skip to main content
Click here to Skip to main content
Go to top

Behavior and Trigger in WPF/Silverlight

, 11 Jun 2012
Rate this:
Please Sign up or sign in to vote.
Behaviors and Triggers explained with samples.

Introduction

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.

Behavior

This can be used to change the behavior of the control independent of ViewModel. For example in the below sample, the Foreground color of check box changed based on Check box state using behavior.

Create a class by inheriting from Behavior and override OnAttached and OnDetaching methods. In the OnAttached you can hook the event and in OnDetaching, you have to unhook the events hooked in the OnAttached. 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>

Using behavior we don’t have to write code behind code. It will help you to develop you application in MVVM.

TriggerAction

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. You have to just override Invoke method. Invoke method will be called when the particular 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>

TargetedTriggerAction

Behavior and TargetTrigger are used to extend the functionality of particular control. TargettedTriggerAction can be used to change the behavior of another control (Target control) based on the actions in the Associated Control. In the below sample, the TextBlock content changed based on checkbox state change.

In XAML, specify EventName using EventTrigger and the Target using TergetedTriggerAction. The Target can be specified using the TargetObject or TargetName property in TargetedTriggerAction. In the below sample TargetObject used. The TagetObject property was added in 4.0 version only. You can’t find this property in the 3.5 version.

<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <CheckBox IsThreeState="True">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <local:TargetedTriggerActionCheckBox TargetObject="{Binding ElementName=MyTextBlock}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </CheckBox>
    <TextBlock x:Name="MyTextBlock"
                Grid.Column="1"
                Margin="5,0"
                Text="False" />
</Grid>

TargetTriggerAction for Checkbox created by inheriting from TargetTriggerAction. T is the Target. Here the Target is TextBlock. When the action takes place, the invoke method will be called with EventArgs. You can do the necessary things here. You can access the check box in TriggerAction by typecasting the AssociatedObject.

public class TargetedTriggerActionCheckBox : TargetedTriggerAction<TextBlock>
{
    protected override void Invoke(object parameter)
    {
        this.Target.Text = (this.AssociatedObject as CheckBox).IsChecked != null ?
            (this.AssociatedObject as CheckBox).IsChecked.ToString() : "Null";
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syncsivakumar
Technical Lead
India India
Working in WPF and Silverlight.
Follow on   Twitter

Comments and Discussions

 
QuestionDon't use the TriggerAction class! PinmemberJames Sean Wright11-Feb-13 22:48 
AnswerRe: Don't use the TriggerAction class! Pinmembersyncsivakumar11-Feb-14 1:44 
GeneralToo Cool Article Pinmemberanup125200010-Sep-12 2:25 
Very nice article.
SuggestionInitial state of TargetedTriggerActionCheckBox PinmvpJani Giannoudis11-Jun-12 22:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 11 Jun 2012
Article Copyright 2012 by syncsivakumar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid