Behaviors/Triggers in code behind

Mar 8, 2013 at 6:34 PM

is possible attach behaviors/triggers in code behind?

            Command="{Binding Path=SaveCommand}"
            Text="{Binding Path=LocalizedResources.Save, Source={StaticResource LocalizedStrings}}" />

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

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