WPF Datagrid ContextMenu MenuItem Command CommandParameter MultiBinding
//xaml <Window x:Class="WpfApp194.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:WpfApp194" mc:Ignorable="d" WindowState="Maximized" Title="MainWindow" Height="450" Width="800"> <Grid> <DataGrid ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" AutoGenerateColumns="False" SelectionUnit="FullRow"> <DataGrid.ContextMenu > <ContextMenu ItemsSource="{Binding BookKindsList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <ContextMenu.ItemTemplate> <DataTemplate> <StackPanel> <MenuItem Header="{Binding Kind}" Command="{Binding DataContext.ShowCmd,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"> <MenuItem.CommandParameter> <MultiBinding Converter="{local:MultiContextMenuConverter}"> <Binding RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=MenuItem}"/> <Binding RelativeSource="{RelativeSource Mode=FindAncestor,AncestorType=DataGrid}"/> </MultiBinding> </MenuItem.CommandParameter> </MenuItem> </StackPanel> </DataTemplate> </ContextMenu.ItemTemplate> </ContextMenu> </DataGrid.ContextMenu> <DataGrid.Columns> <DataGridTextColumn Header="Id" Binding="{Binding Id}"/> <DataGridTextColumn Header="Name" Binding="{Binding Name}"/> </DataGrid.Columns> </DataGrid> </Grid> </Window> //cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApp194 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var vm = new BKVM(); this.DataContext = vm; } } public class BKVM : INotifyPropertyChanged { public BKVM() { InitData(); InitCmds(); } private void InitCmds() { ShowCmd = new DelCmd(ShowCmdExecuted); } public void ShowCmdExecuted(object obj) { var objArray= (object[])obj; if(objArray!=null && objArray.Count()==2) { var selectedMenuItem = objArray[0] as MenuItem; var selectedDg = objArray[1] as DataGrid; if(selectedDg!=null && selectedMenuItem!=null) { var selectedBk = selectedDg.SelectedItem as Book; var selectedBkKind = selectedMenuItem.DataContext as BookKind; if (selectedBk!=null && selectedBkKind!=null) { string str = $"Selected Book Id:{selectedBk.Id},Name:{selectedBk.Name}\nSelectedBookKind:{selectedBkKind.ToString()}"; MessageBox.Show(str, $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}"); } } } } public bool ShowCmdCanExecute(object obj) { return true; } private void InitData() { BooksList = new List<Book>(); for (int i = 0; i < 1000; i++) { Book bk = new Book() { Id = i + 1, Name = $"Name_{i + 1}" }; BooksList.Add(bk); } BookKindsList = new List<BookKind>(); for (int i = 0; i < 5; i++) { BookKind bk = new BookKind() { Idx = i + 1, Kind = $"Kind_{i + 1}" }; BookKindsList.Add(bk); } } #region Properties private List<BookKind> bookKindsList; public List<BookKind> BookKindsList { get { return bookKindsList; } set { bookKindsList = value; OnPropertyChanged(nameof(BookKindsList)); } } public DelCmd ShowCmd { get; set; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { var handler = PropertyChanged; if (handler != null) { handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } private List<Book> booksList; public List<Book> BooksList { get { return booksList; } set { if (value != booksList) { booksList = value; OnPropertyChanged(nameof(BooksList)); } } } #endregion } public class Book { public int Id { get; set; } public string Name { get; set; } } public class BookKind { public int Idx { get; set; } public string Kind { get; set; } public override string ToString() { return $"\nIdx:{Idx},Kind:{Kind}"; } } public class DelCmd : ICommand { private Action<object> _execute; private Predicate<object> _canExecute; public DelCmd(Action<object> executeValue, Predicate<object> canExecuteValue) { _execute = executeValue; _canExecute = canExecuteValue; } public DelCmd(Action<object> executeValue) : this(executeValue, null) { } public event EventHandler CanExecuteChanged; protected virtual void RaiseExecuteChanged(object sender, ExecutedRoutedEventArgs e) { var handler = CanExecuteChanged; if (handler != null) { handler(this, e); } } public bool CanExecute(object parameter) { if (_canExecute == null) { return true; } return _canExecute(parameter); } public void Execute(object parameter) { _execute(parameter); } } public class MultiContextMenuConverter : MarkupExtension, IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { return values.ToArray(); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } private static MultiContextMenuConverter multiConvertInstance; public override object ProvideValue(IServiceProvider serviceProvider) { if(multiConvertInstance == null) { multiConvertInstance = new MultiContextMenuConverter(); } return multiConvertInstance; } } }