WPF dynamically generate contextmenu on datagrid via viewmodel, binding matched command of viewmodel
The key of dynamically generated contextmenu and menuitems is to bind command to appropriate command in viewmodel.
<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}}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=MenuItem}}"/> </StackPanel> </DataTemplate> </ContextMenu.ItemTemplate> </ContextMenu> </DataGrid.ContextMenu>
//Whole code
//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}}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=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.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.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 selectedMenuItem = obj as MenuItem; if (selectedMenuItem != null) { var selectedBkKind = selectedMenuItem.DataContext as BookKind; if (selectedBkKind != null) { MessageBox.Show(selectedBkKind.ToString(), $"{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); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2019-07-04 C# based on PdfSharp to split pdf files and get MemoryStream C#基于PdfSharp拆分pdf,并生成MemoryStream