How to use ContextMenu UserControl in WPF?

I have a user control as follows:

<UserControl x:Class="MyApp.UserControls.MyContextMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d"
             ContextMenuOpening="OnContextMenuOpening"
             d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.ContextMenu>
        <ContextMenu>
        ...
        </ContextMenu>
    </UserControl.ContextMenu>
</UserControl>

My question is: how do I use this context menu for something like a data grid:

<DataGrid ContextMenu="{usercontrols:MyContextMenu}"

Unfortunately, this does not work, because the specified value is incorrect and a is expected ContextMenu.

Note. I need to reuse the context menu in several places, so I put it in my own file. In addition, I need to be able to listen to events OnContextMenuOpening, because the menu, when opened, should do some work on the menu, and the event does not fire for the context menu: http://connect.microsoft.com/VisualStudio/feedback/details/353112/contextmenu- opening-event-doesnt-fire-properly

"ContextMenu FrameworkElement, , . , " " , .

, - .

: :

enter image description here

:

enter image description here

: ContextMenu cannot have a logical or visual parent.

+5
2

, UserControl, ContextMenu. ContextMenu UserControl:

<ContextMenu x:Class="MyApp.MyContextMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <MenuItem Header="Item 1"/>
    <MenuItem Header="Item 2"/>
    ...
</ContextMenu>

public partial class MyContextMenu : ContextMenu
{
    public MyContextMenu()
    {
        InitializeComponent();
    }
}

?

+7

:

<DataGrid.Resources>
    <ContextMenu x:Key="DgContextMenu">
      ...
    </ContextMenu>
</DataGrid.Resources>

<DataGrid ContextMenu="{StaticResource DgContextMenu}

.

+3

All Articles