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);
        }
    }
}

 

 

 

posted @ 2024-07-04 17:44  FredGrit  阅读(2)  评论(0编辑  收藏  举报