Using MVVM, how can a ContextMenu ViewModel find the ViewModel that opened the ContextMenu?

北城余情 提交于 2019-12-04 03:56:29

There's a DP on the ContextMenu object called "PlacementTarget" - this will be set to the UI element the context menu is attached to - you can even use it as a Binding source, so you could pass it along to your Command via CommandParameter:

http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu.placementtarget.aspx

edit: in your case, you'd want the VM of the PlacementTarget, so your binding would probably look more like:

{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}

I solved this by handling the ContextMenuOpening event on the parent control (the one that owned the ContextMenu in the View). I also added a Context property to IMenuItem. The handler looks like this:

    private void stackPanel_ContextMenuOpening(
        object sender, ContextMenuEventArgs e)
    {
        StackPanel sp = sender as StackPanel;
        if (sp != null)
        {
            // solutionItem is the "context"
            ISolutionItem solutionItem =
                sp.DataContext as ISolutionItem;
            if (solutionItem != null) 
            {
                IEnumerable<IMenuItem> items = 
                    solutionItem.ContextMenu as IEnumerable<IMenuItem>;
                if (items != null)
                {
                    foreach (IMenuItem item in items)
                    {
                        // will automatically set all 
                        // child menu items' context as well
                        item.Context = solutionItem;
                    }
                }
                else
                {
                    e.Handled = true;
                }
            }
            else
            {
                e.Handled = true;
            }
        }
        else
        {
            e.Handled = true;
        }
    }

This takes advantage of the fact that there can only be one ContextMenu open at a time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!