How to share a ContextMenu in WPF

To share a ContextMenu by multiple controls, we need to create a ContextMenu as a resource. A resource can be created on a control level, a Window or Page level, or application level. The resources created on a control level can be used within that control and its child controls only. The resources created on a Window or a Page level can be used within that window or page only. The resources created globally can be shared from anywhere within that application.

The code in Listing creates a ContextMenu resource on a Window level and later ContextMenu property to this ContextMenu using DynamicResource.

<Window x:Class="ContextMenuWPFSample.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="300" Width="300">

 

    <Window.Resources>

        <!-- Create a Shared ContextMenu -->

        <ContextMenu x:Key="SharedContextMenu" x:Shared="true">

            <MenuItem Header="Color" IsCheckable="true" />

            <Separator/>

            <MenuItem Header="Shape" />

        </ContextMenu>

 

 

    </Window.Resources>

 

    <Canvas >

       

        <Button Background="LightBlue" Canvas.Top="140" Canvas.Left="20"

            Width="120" Height="32"

            Content="Right Click Me"

            ContextMenu="{DynamicResource SharedContextMenu}" />

        <TextBox Background="LightBlue" Canvas.Top="180" Canvas.Left="20"

            Width="120" Height="32"

             Text="Right Click TextBox"

            ContextMenu="{DynamicResource SharedContextMenu}" />

    </Canvas>

</Window>

 

Now if you run and execute this and right click on Button or TextBox, you will see same ContextMenu.