<Window x:Class="WpfApp_GridContextMenu.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="208" HorizontalAlignment="Left" Margin="79,50,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="319" ContextMenuOpening="dataGrid1_ContextMenuOpening">
<DataGrid.ContextMenu>
<ContextMenu>
<MenuItem Header="aaaaa" x:Name="m1"/>
<MenuItem Header="bbb" x:Name="m2"/>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding Path=ID}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Name}"/>
<DataGridTextColumn Header="Status" Binding="{Binding Path=Status}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
private void dataGrid1_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
if (e.OriginalSource is ScrollViewer)
{
e.Handled = true;
}
Person p = this.dataGrid1.SelectedItem as Person;
if (p != null)
{
e.Handled = false;
m1.IsEnabled = p.Status == 1;
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_lst.Add(new Person { ID = 1, Name = "1", Status = 1 });
_lst.Add(new Person { ID = 2, Name = "2", Status = 2 });
_lst.Add(new Person { ID = 3, Name = "3", Status = 3 });
this.dataGrid1.ItemsSource = _lst;
}
private ObservableCollection<Person> _lst = new ObservableCollection<Person>();