Behaviors/Triggers in code behind

Mar 8, 2013 at 6:34 PM
Hi,

is possible attach behaviors/triggers in code behind?

Thanks
    <i:Interaction.Behaviors>
        
        <appBar:AppBarItemCommand
            Command="{Binding Path=SaveCommand}"
            Id="save"
            Text="{Binding Path=LocalizedResources.Save, Source={StaticResource LocalizedStrings}}" />

    </i:Interaction.Behaviors>
Coordinator
May 23, 2013 at 6:02 AM
Hi there,

Yeah, you can definitely do this. Basically everything you can do in XAML, you can also do in code behind.

Here's how. The Interaction.Behaviors is actually an attached property you can set for every dependency object like below. Thus the rest is to provide a proper value for that attached property. Since it represents a collection of behaviors rather than a single behavior, so you'll have to explicitly work with the BehaviorCollection. Here's the code with comments:
// Obtain the BehaviorCollection for the target dependency object, such as the LayoutRoot grid
var behaviors = Interaction.GetBehaviors(targetDpObj);

// Create the behavior that you want to attach
var appBarItemCommand = new AppBarItemCommand();

// Set AppBarItemCommand properties ...

// Add the behavior to BehaviorCollection
behaviors.Add(appBarItemCommand);

// Set the Interaction.Behaviors attached property to the target dependency object
targetDpObj.SetValue(Interaction.BehaviorsProperty, behaviors);
As you can see, it's kind of verbose here. So only do it in code behind when you really have to.

Thanks/Allen