I want to add new row on right click- Insert menu on EmpName column but it's not firing InsertCommand. I have enclosed the xaml code here. Please tell me what am I missing here.
<Window x:Class="DataGridRowsManagement.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:data="clr-namespace:DataGridRowsManagement"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<data:ViewModel x:Key="EmpVM"></data:ViewModel>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource EmpVM}}">
<DataGrid AutoGenerateColumns="False" Height="287"
HorizontalAlignment="Left" Margin="23,12,0,0"
Name="dgEmp" VerticalAlignment="Top" Width="657"
ItemsSource="{Binding Path=Employees}" ColumnWidth="*"
SelectedIndex="{Binding Path=RecordIndex,Mode=TwoWay}">
<DataGrid.Columns>
<DataGridTextColumn Header="EmpNo" Binding="{Binding EmpNo}" />
<DataGridTemplateColumn Header="EmpName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding EmpName}" HorizontalAlignment="Stretch">
<TextBlock.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}">
<MenuItem Command="{Binding InsertCommand}" CommandParameter="{Binding RecordIndex}" Header="Insert"/>
<MenuItem Command="{Binding DeleteCommand}" CommandParameter="{Binding RecordIndex}" Header="Delete"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="Salary" Binding="{Binding Salary}" />
<DataGridTextColumn Header="Designation" Binding="{Binding Designation}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Those bindings are inside a
DataTemplate, so those will try to bind to the item that is going to be templated. Also, since this is insideContextMenu, you need to use thex:Reference.Try the next: