Attach behavior in code behind Attach behavior in code behind wpf wpf

Attach behavior in code behind


XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding()     {         ElementName = "_uc",         Path = new PropertyPath("SelectedItems"),         Mode = BindingMode.TwoWay     });Interaction.GetBehaviors(yourElementName).Add(behavior)


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)