vikas mittal
vikas mittal

Reputation: 675

How to add WPF Behavior in the code behind

I am trying to find a way to add behavior in the code, I am able to add it successfully in XAML.

This is how I am adding the behavior in XAML to a grid, SelectedItems is a DP in the behavior and it is data bind to the view model selected items property. I am listening to the grid collection changed event and updating the DP which in turns notify the view mode of the selected items

/// <summary>
/// Dependency Property SelectedItems
/// </summary>
public static readonly DependencyProperty SelectedItemsProperty =
        DependencyProperty.Register("SelectedItems", 
        typeof(INotifyCollectionChanged), typeof(MultiSelectBehavior), 
        new PropertyMetadata(null));

AssociatedObject.SelectedItems.CollectionChanged += GridSelectedItems_CollectionChanged;
<i:Interaction.Behaviors>                
    <behaviors:MultiSelectBehavior SelectedItems="{Binding SelectedItems}"/>
</i:Interaction.Behaviors>

What I need is to create this behavior in the code behind. I am doing this in the constructor of the window that contains the grid, but it is not working, the viewmodel selected items property is not getting updated.

var multiSelectBehavior = new MultiSelectBehaviorSingleton();
BindingOperations.SetBinding(this.BackupsGrid, MultiSelectBehavior.SelectedItemsProperty, 
    new Binding()
    {
        Source = this.DataContext,
        Path = new PropertyPath("SelectedItems"),
        Mode = BindingMode.OneWay
    });
Interaction.GetBehaviors(this.BackupsGrid).Add(multiSelectBehavior);

Upvotes: 3

Views: 2395

Answers (2)

mark.monteiro
mark.monteiro

Reputation: 2931

The accepted answer does not appear to work in the designer, because the OnAttached event is never raised. An approach that works at runtime and also in the designer is using the Attach() method on the behavior. In this case, that would look like this:

var multiSelectBehavior = new MultiSelectBehavior();
BindingOperations.SetBinding(multiSelectBehavior, MultiSelectBehavior.SelectedItemsProperty, new Binding("SelectedItems"));
multiSelectBehavior.Attach(this.BackupsGrid)

Upvotes: 2

mm8
mm8

Reputation: 169228

Try this:

var multiSelectBehavior = new MultiSelectBehavior();
BindingOperations.SetBinding(multiSelectBehavior, MultiSelectBehavior.SelectedItemsProperty, new Binding("SelectedItems"));
Interaction.GetBehaviors(this.BackupsGrid).Add(multiSelectBehavior);

Upvotes: 3

Related Questions