Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 221
vikas mittal Avatar asked Jun 06 '26 14:06

vikas mittal


2 Answers

Try this:

var multiSelectBehavior = new MultiSelectBehavior();
BindingOperations.SetBinding(multiSelectBehavior, MultiSelectBehavior.SelectedItemsProperty, new Binding("SelectedItems"));
Interaction.GetBehaviors(this.BackupsGrid).Add(multiSelectBehavior);
like image 135
mm8 Avatar answered Jun 09 '26 03:06

mm8


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)
like image 26
mark.monteiro Avatar answered Jun 09 '26 04:06

mark.monteiro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!