Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attach behavior in code behind

I have the following Xaml that is used in a user control that used as an editor inside a property grid. The question is, what would the c# look like to attach a behavior from the code behind?

<i:Interaction.Behaviors>
    <igExt:XamComboEditorSelectedItemsBehavior SelectedItems="{Binding SelectedItems, ElementName=_uc}"/>
</i:Interaction.Behaviors>

Since this is on an editor that is loaded dynamically in a PropertyGrid, I was just going to create an instance of the editor with binding from code behind rather than having to have different xaml files that are really short and just contain one editor.

Or would it be easier to simply re implement all of the code that is in the Behavior and call it while I'm creating the editor in the code behind?

like image 470
BrandonAGr Avatar asked May 02 '12 22:05

BrandonAGr


2 Answers

XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();
behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() 
    { 
        ElementName = "_uc", 
        Path = new PropertyPath("SelectedItems"), 
        Mode = BindingMode.TwoWay 
    });
Interaction.GetBehaviors(yourElementName).Add(behavior)
like image 189
EvAlex Avatar answered Sep 27 '22 23:09

EvAlex


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:

XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();
behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() 
    { 
        ElementName = "_uc", 
        Path = new PropertyPath("SelectedItems"), 
        Mode = BindingMode.TwoWay 
    });
multiSelectBehavior.Attach(yourElementName)
like image 43
mark.monteiro Avatar answered Sep 27 '22 23:09

mark.monteiro