0

我有一个自定义形状 - MyShape- (可能是控制,没关系)。

MyShape有一个装饰器 - TextAdorner

TextAdorner应该具有相同的 ContextMenu (MyShape因为它们代表相同的唯一对象)。

MyShape 的 CustomMenu 在某些情况下在代码中发生了更改。因此,我需要检测MyShape更改其 CustomMenu 以更新装饰器 ContextMenu 的时刻。

但是,没有ContextMenuChanging, 也没有ContextMenuChanged事件。

我将此代码用于第一个 ContemxtMenu 分配,但是当装饰元素更改上下文菜单时,我不知道如何同步它们。

public class TextAdorner : Adorner
{
    public TextAdorner(UIElement adornedElement)
        : base(adornedElement)
    {
        this.ContextMenu = (adornedElement as MyShape).ContextMenu;
    }

在这种情况下我应该如何进行?

4

2 回答 2

2

不只是分配 ContextMenu 属性,而是创建一个 Binding。这样,框架将为您处理更新。您可以使用 adornedElement 参数作为源创建绑定,如下所示:

public class TextAdorner : Adorner
{
    public TextAdorner(UIElement adornedElement)
        : base(adornedElement)
    {
        BindingOperations.SetBinding(
            this,
            FrameworkElement.ContextMenuProperty,
            new Binding
            {
                Path = new PropertyPath(FrameworkElement.ContextMenuProperty),
                Source = adornedElement
            });
    }

您还可以使用 Adorner 上的 AdornedElement 属性进行绑定:

BindingOperations.SetBinding(
    this,
    FrameworkElement.ContextMenuProperty,
    new Binding("AdornedElement.ContextMenu")
    {
        RelativeSource = RelativeSource.Self
    });

如果您需要在 XAML 中指定绑定,则此方法将起作用:

<Something ContextMenu="{Binding AdornedElement.ContextMenu, 
    RelativeSource={RelativeSource Self}}"/>
于 2010-11-25T13:21:01.703 回答
1

ContextMenu您想要的是在属性上创建从MyShape对象到您的单向绑定TextAdorner

所以 :

public class TextAdorner : Adorner
{
    public TextAdorner(UIElement adornedElement)
        : base(adornedElement)
    {
        Binding myBinding = new Binding("ContextMenu");
        myBinding.Source = (adornedElement as MyShape);
        this.SetBinding(FrameworkElement.ContextMenuProperty,myBinding);
    }
}

参考:http: //msdn.microsoft.com/en-us/library/ms742863.aspx

于 2010-11-25T13:20:30.420 回答