WPF ContextMenu Example

Kailash Chandra Behera | Tuesday, September 08, 2020

Introduction

WPF ContextMenu is used to display a list of WPF MenuItems in the vertical order inside any WPF Control. Here in this blog, we will demonstrate how to create and use the WPF ContextMenu in WPF.

WPF ContextMenu Example

WPF ContextMenu

Getting Started

A WPF ContextMenu is used to attach to specific control like (DataGrid, TreeView, and Button, etc.) and appears when the user right-clicks on the control.

it represents a list of elements (MenuItem, button, textbox, etc.) as a context and specifies commands or options that are associated with a particular control, for example, a DataGrid. The elements inside ContextMenu can perform their actions n individually.

Demonstration

This demonstration is will create WPF ContextMenu using XAML code and c# code in the WPF RitchTextbox, will style it, and customize it for better appearance, using ContextMenu we will command the Richtextbox for text copy, paste and cut action.

Create ContextMenu using XAML

The following example creates a ContextMenu inside the RichTextbox with three MenuItems. These MenuItems will use to fire command for copy, paste, and cut action.

 <Window x:Class="ContextMenuExample.MainWindow"  
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
     xmlns:local="clr-namespace:ContextMenuExample"  
     mc:Ignorable="d"  
     Title="MainWindow" Height="450" Width="800">  
   <RichTextBox Name="rtbnotepad">  
     <RichTextBox.ContextMenu>  
       <ContextMenu>  
         <MenuItem Header="_Copy" InputGestureText="Ctrl+C" Command="ApplicationCommands.Copy"/>  
         <MenuItem Header="_Cut" InputGestureText="Ctrl+X" Command="ApplicationCommands.Cut"/>  
         <MenuItem Header="_Paste" InputGestureText="Ctrl+P" Command="ApplicationCommands.Paste"/>  
         <MenuItem Header="_Delete" InputGestureText="Ctrl+P" Command="ApplicationCommands.Delete"/>  
       </ContextMenu>  
     </RichTextBox.ContextMenu>  
   </RichTextBox>  
 </Window>  
Create ContextMenu using C#

The following example creates a ContextMenu inside the RichTextbox using c# code, it can be used to create and attach ContextMenu at run time to any WPF Controls.

  private void CreatContextMenu()  
     {  
       //initilize ContextMenu  
       ContextMenu contextMenu = new ContextMenu();  
       //Copy Menu  
       MenuItem menuItem_copy = new MenuItem();  
       menuItem_copy.Header = "_Copy";  
       menuItem_copy.Command = ApplicationCommands.Copy;  
       //Adding chicld element to contextmenu  
       contextMenu.Items.Add(menuItem_copy);  
       //Paste Menu  
       MenuItem menuItem_paste = new MenuItem();  
       menuItem_paste.Header = "Paste";  
       menuItem_paste.Command = ApplicationCommands.Paste;  
       contextMenu.Items.Add(menuItem_paste);  
       //Cut Menu  
       MenuItem menuItem_cut = new MenuItem();  
       menuItem_cut.Header = "_Cut";  
       menuItem_cut.Command = ApplicationCommands.Cut;  
       contextMenu.Items.Add(menuItem_cut);  
       //Delete Menu  
       MenuItem menuItem_delete = new MenuItem();  
       menuItem_delete.Header = "Delete";  
       menuItem_delete.Command = ApplicationCommands.Delete;  
       contextMenu.Items.Add(menuItem_delete);  
       //Attach ContextMenu to richtextbox  
       this.rtbnotepad.ContextMenu = contextMenu;  
     }  
Customize WPF ContextMenu

Like other WPF controls, the appearance of ContextMenu can be also changed using XAML code as well as C# code. Here in the following example shows, how to add a border control to the context menu to change the appearance. The border control will appear at the edge of ContextMenu with round corner shape.

 <ContextMenu Height="200" Width="150">  
         <ContextMenu.Template>  
           <ControlTemplate>  
             <Border BorderBrush="DarkGray" CornerRadius="10" BorderThickness="1,1,3,3">  
               <StackPanel Orientation="Vertical">  
                 <MenuItem Header="_Copy" InputGestureText="Ctrl+C" Command="ApplicationCommands.Copy"/>  
                 <MenuItem Header="_Cut" InputGestureText="Ctrl+X" Command="ApplicationCommands.Cut"/>  
                 <MenuItem Header="_Paste" InputGestureText="Ctrl+P" Command="ApplicationCommands.Paste"/>  
                 <MenuItem Header="_Delete" InputGestureText="Ctrl+P" Command="ApplicationCommands.Delete"/>  
               </StackPanel>  
             </Border>  
           </ControlTemplate>  
         </ContextMenu.Template>  
       </ContextMenu>  

The same thing you can do by applying a style to the context menu. Using style you can change the appearance of the context menu as well as the chile element at a time. The following example doing the same thing that the above example did, it changes the appearance of the default context menu to rounded context menu.

 <RichTextBox.ContextMenu>  
       <ContextMenu>  
         <ContextMenu.Style>  
           <Style TargetType="{x:Type ContextMenu}">  
             <Setter Property="SnapsToDevicePixels"  
      Value="True" />  
             <Setter Property="OverridesDefaultStyle"  
      Value="True" />  
             <Setter Property="Grid.IsSharedSizeScope"  
      Value="true" />  
             <Setter Property="HasDropShadow"  
      Value="True" />  
             <Setter Property="Template">  
               <Setter.Value>  
                 <ControlTemplate TargetType="{x:Type ContextMenu}">  
                   <Border x:Name="Border"  
         Background="{StaticResource MenuPopupBrush}"  
         BorderThickness="1,1,3,3">  
                     <Border.BorderBrush>  
                       <SolidColorBrush Color="{StaticResource BorderMediumColor}" />  
                     </Border.BorderBrush>  
                     <StackPanel IsItemsHost="True"  
            KeyboardNavigation.DirectionalNavigation="Cycle" />  
                   </Border>  
                   <ControlTemplate.Triggers>  
                     <Trigger Property="HasDropShadow"  
           Value="true">  
                       <Setter TargetName="Border"  
           Property="Padding"  
           Value="0,3,0,3" />  
                       <Setter TargetName="Border"  
           Property="CornerRadius"  
           Value="4" />  
                     </Trigger>  
                   </ControlTemplate.Triggers>  
                 </ControlTemplate>  
               </Setter.Value>  
             </Setter>  
           </Style>  
         </ContextMenu.Style>  
         <MenuItem Header="_Copy" InputGestureText="Ctrl+C" Command="ApplicationCommands.Copy"/>  
         <MenuItem Header="_Cut" InputGestureText="Ctrl+X" Command="ApplicationCommands.Cut"/>  
         <MenuItem Header="_Paste" InputGestureText="Ctrl+P" Command="ApplicationCommands.Paste"/>  
         <MenuItem Header="_Delete" InputGestureText="Ctrl+P" Command="ApplicationCommands.Delete"/>  
       </ContextMenu>  
     </RichTextBox.ContextMenu>  
Applying Styles

By using a control Style, you can dramatically change the appearance and behavior of a ContextMenu without writing a custom control. In addition to setting visual properties, you can also apply styles to parts of the control. For example, you can change the behavior of parts of the control by using properties, or you can add parts to, or change the layout of, a ContextMenu. The following examples show several ways to add styles to ContextMenu controls.

The first example defines a style called SimpleSysResources, which shows how to use the current system settings in your style. The example assigns MenuHighlightBrushKey as the Background color and MenuTextBrushKey as the Foreground color of the ContextMenu.

 <Style x:Key="SimpleSysResources" TargetType="{x:Type MenuItem}">   
  <Setter Property = "Background" Value=  
   "{DynamicResource {x:Static SystemColors.MenuHighlightBrushKey}}"/>   
  <Setter Property = "Foreground" Value=  
   "{DynamicResource {x:Static SystemColors.MenuTextBrushKey}}"/>   
 </Style>  

The following example uses the Trigger element to change the appearance of a Menu in response to events that are raised on the ContextMenu. When a user moves the mouse over the menu, the appearance of the ContextMenu items changes.

 <Style x:Key="Triggers" TargetType="{x:Type MenuItem}">   
  <Style.Triggers>   
   <Trigger Property="MenuItem.IsMouseOver" Value="true">   
    <Setter Property = "FontSize" Value="16"/>   
    <Setter Property = "FontStyle" Value="Italic"/>   
    <Setter Property = "Foreground" Value="Red"/>   
   </Trigger>   
  </Style.Triggers>   
 </Style>  

Summary

In this blog, we learn how to create WPF ContextMenu and attache to WPF Control using XAML and c#, customize the menu and many more. I hope you have enjoyed it a lot.

Thanks