C# 在代码隐藏中附加行为

C# 在代码隐藏中附加行为,c#,wpf,xaml,mvvm,code-behind,C#,Wpf,Xaml,Mvvm,Code Behind,我有以下Xaml,用于在属性网格中用作编辑器的用户控件中。问题是,从代码背后附加行为时,c#会是什么样子 <i:Interaction.Behaviors> <igExt:XamComboEditorSelectedItemsBehavior SelectedItems="{Binding SelectedItems, ElementName=_uc}"/> </i:Interaction.Behaviors> XamComboEditorSelec

我有以下Xaml,用于在属性网格中用作编辑器的用户控件中。问题是,从代码背后附加行为时,c#会是什么样子

<i:Interaction.Behaviors>
    <igExt:XamComboEditorSelectedItemsBehavior SelectedItems="{Binding SelectedItems, ElementName=_uc}"/>
</i:Interaction.Behaviors>
XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();
behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() 
    { 
        ElementName = "_uc", 
        Path = new PropertyPath("SelectedItems"), 
        Mode = BindingMode.TwoWay 
    });
Interaction.GetBehaviors(yourElementName).Add(behavior)

因为这是在一个动态加载到PropertyGrid中的编辑器上,所以我只是想创建一个编辑器实例,并从代码隐藏中绑定,而不是必须有不同的xaml文件,这些文件非常短,只包含一个编辑器


或者,当我在“代码隐藏”中创建编辑器时,简单地重新实现行为中的所有代码并调用它会更容易吗?

接受的答案在设计器中似乎不起作用,因为从未引发
OnAttached
事件。一种在运行时和设计器中都有效的方法是对行为使用
Attach()
方法。在这种情况下,看起来是这样的:

<i:Interaction.Behaviors>
    <igExt:XamComboEditorSelectedItemsBehavior SelectedItems="{Binding SelectedItems, ElementName=_uc}"/>
</i:Interaction.Behaviors>
XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();
behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() 
    { 
        ElementName = "_uc", 
        Path = new PropertyPath("SelectedItems"), 
        Mode = BindingMode.TwoWay 
    });
Interaction.GetBehaviors(yourElementName).Add(behavior)
XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();
behavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() 
    { 
        ElementName = "_uc", 
        Path = new PropertyPath("SelectedItems"), 
        Mode = BindingMode.TwoWay 
    });
multiSelectBehavior.Attach(yourElementName)

行为不只是一个项目集合吗?如果是这样,只需使用myInteraction.Behaviors.Add(新的XamComboEditorSelectedItemsBehavior{//set props});我没有发现任何直接影响行为的挫折方法。相反,我不得不使用BindingOperations.SetBinding()来代替