Click here to Skip to main content
15,881,139 members
Articles / Desktop Programming / WPF
Tip/Trick

Behavior and Trigger in WPF/Silverlight

Rate me:
Please Sign up or sign in to vote.
4.85/5 (8 votes)
11 Jun 2012CPOL2 min read 57.3K   2.3K   16   6
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.

C#
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.

XML
<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.

C#
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.

XML
<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.

XML
<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.

C#
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)


Written By
Technical Lead
India India
Working in WPF and Silverlight.

Comments and Discussions

 
QuestionCallMethodAction 5 stars Pin
Fabrizio Stellato29-Jul-15 21:32
Fabrizio Stellato29-Jul-15 21:32 
QuestionDon't use the TriggerAction class! Pin
James Wright_11-Feb-13 22:48
professionalJames Wright_11-Feb-13 22:48 
AnswerRe: Don't use the TriggerAction class! Pin
syncsivakumar11-Feb-14 1:44
syncsivakumar11-Feb-14 1:44 
GeneralToo Cool Article Pin
Anup Raghavendra Hosur10-Sep-12 2:25
professionalAnup Raghavendra Hosur10-Sep-12 2:25 
SuggestionInitial state of TargetedTriggerActionCheckBox Pin
Jani Giannoudis11-Jun-12 22:52
Jani Giannoudis11-Jun-12 22:52 

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

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