How to create a ContextMenu in WPF

You can add a ContextMenu to any control by using control's ContextMenu property. For example, this code adds a ContextMenu to a Rectangle.

<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">
    <Canvas >

        <Rectangle Name="BlueRectangle"
                   Width="200" Height="100"
                   Canvas.Left="20" Canvas.Top="20"
                   Fill="LightBlue">

            <Rectangle.ContextMenu>
                <ContextMenu Name="RectangleMenu">
                    <MenuItem Header="Color">
                        <MenuItem Header="Red" Click="RedMenuItem_Click" />
                        <MenuItem Header="Green" Click="GreenMenuItem_Click"/>
                        <MenuItem Header="Orange" Click="OrangeMenuItem_Click"/>                       
                    </MenuItem>                   
                </ContextMenu>
            </Rectangle.ContextMenu>
           
        </Rectangle>
    </Canvas>
</Window>