WPF DataGrid Context Menu

Introduction

This blog provides code examples of how to add the WPF context menu into WPF Datagrid using XAML code and at run time using C# code.

WPF DataGrid Context Menu using XAML

The following below XAML code adds the WPF context menu into WPF Datagrid. Which contains three menus (Add, Edit and Delete)

 <DataGrid Name="dgcontextmenu" AutoGenerateColumns="False">  
       <DataGrid.Columns>  
         <DataGridTextColumn Header="Employee ID" Binding="{Binding Path=ID}"/>  
         <DataGridTextColumn Header="Employee Name" Binding="{Binding Path=Name}"/>  
         <DataGridTextColumn Header="Employee Post" Binding="{Binding Path=Post}"/>  
       </DataGrid.Columns>  
       <DataGrid.ContextMenu>  
         <ContextMenu>  
           <MenuItem Header="_Add" />  
           <MenuItem Header="_Edit"/>  
           <MenuItem Header="_Delete"/>  
         </ContextMenu>  
       </DataGrid.ContextMenu>  
     </DataGrid>  

WPF DataGrid Context Menu

WPF DataGrid Context Menu using C#

The following below code adds the WPF context menu into WPF Datagrid using C#. you can use this code to add WPF context menu into WPF Datagrid at run time.

 this.dgcontextmenu.ItemsSource = emps;  
   
       ContextMenu contextMenu = new ContextMenu();  
   
       MenuItem menuItem_add = new MenuItem();  
       menuItem_add.Header = "_Add";  
       menuItem_add.Command = ApplicationCommands.New;  
   
       contextMenu.Items.Add(menuItem_add);  
   
       MenuItem menuItem_edit = new MenuItem();  
       menuItem_edit.Header = "_Edit";  
       menuItem_edit.Command = ApplicationCommands.Copy;  
   
       contextMenu.Items.Add(menuItem_edit);  
   
       MenuItem menuItem_delete = new MenuItem();  
       menuItem_delete.Header = "_Delete";  
       menuItem_delete.Command = ApplicationCommands.Delete;  
   
       contextMenu.Items.Add(menuItem_delete);  
   
       this.dgcontextmenu.ContextMenu = contextMenu;  

WPF DataGrid Context Menu

Summary

In the above code examples, we learn how to add WPF Context menu int WPF datagrid using XAML code and C# code. I hope you have enjoyed it a lot.

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال