在代码后台中附加行为

10

我有以下Xaml,它用于用户控件中,作为属性网格内部编辑器使用。问题是,从代码后台附加行为的C#代码应该是什么样子的?

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

因为这个编辑器是在PropertyGrid中动态加载的,所以我只打算在代码后台创建一个带有绑定的编辑器实例,而不是必须拥有许多非常短并且只包含一个编辑器的不同xaml文件。

或者重新实现行为中的所有代码,并在代码后台创建编辑器时调用它,会更容易吗?


行为不就是一个ItemCollection吗?如果是这样,只需使用myInteraction.Behaviors.Add(new XamComboEditorSelectedItemsBehavior { // set props }); - phixed
2个回答

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

11
在行为(Behavior)上,我没有直接找到SetBinding方法。相反,我不得不使用BindingOperations.SetBinding()方法。 - SwissCoder

2

接受的答案似乎在设计师中不起作用,因为OnAttached事件从未被触发。一个既可以在运行时又可以在设计师中使用的方法是在行为上使用Attach()方法。在这种情况下,代码如下:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接