Search code examples
.netwpfwpf-controlsadorner

No ContextMenuChanging(ed) event in WPF


I have a custom Shape - MyShape - (may be control, does not matter).

MyShape has an adorner - TextAdorner.

The TextAdorner should have the same ContextMenu as MyShape (because they represents the same unique object).

The CustomMenu of MyShape is changed in the code in some conditions. So, I need to detect the moment when MyShape changes its CustomMenu to update the adorner ContextMenu too.

However, there is no ContextMenuChanging, nor ContextMenuChanged events.

I use this code for first ContemxtMenu assignment, however when the adorned element changes the context menu, I don't know how to synchronize them.

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

How should I proceed in this situation?


Solution

  • What you want is to create a one-way binding on the ContextMenu property from your MyShape object to your TextAdorner

    so :

    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);
        }
    }
    

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