首页 > 其他分享 >WPF Datagrid ContextMenu MenuItem Command CommandParameter MultiBinding

WPF Datagrid ContextMenu MenuItem Command CommandParameter MultiBinding

时间:2024-07-04 18:32:22浏览次数:1  
标签:CommandParameter ContextMenu Windows object System Datagrid using null public

 

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

 

 

 

 

 

 

 

 

 

标签:CommandParameter,ContextMenu,Windows,object,System,Datagrid,using,null,public
From: https://www.cnblogs.com/Fred1987/p/18284416

相关文章

  • C#实现禁用DataGridView控件列表头自动排序功能 (附完整源码)
    C#实现禁用DataGridView控件列表头自动排序功能代码说明:在C#中,可以通过设置DataGridView控件的列的SortMode属性来禁用列头的自动排序功能。以下是一个完整的示例代码,展示了如何实现这一功能:usingSystem;usingSystem.Windows.Forms;​namespace......
  • WPF/C#:在DataGrid中显示选择框
    前言在使用WPF的过程中可能会经常遇到在DataGrid的最前或者最后添加一列选择框的需求,今天跟大家分享一下,在自己的项目中是如何实现的。整体实现效果如下:如果对此感兴趣,可以接下来看具体实现部分。实践假设数据库中的模型如下:publicclassPerson{publicintId......
  • dataGridView 常用属性和方法
    ContextMenuStrip属性:当用户点击鼠标右键时(设置和contextMenuStrip挂钩)MultiSelect属性是否可以多行选择SelectionMode属性:设置选中方式,比如是否选中一整行(设置为FullRowSelect)Dock属性:设置显示位置AllowUserToAddRows属性:取消表格中末尾的空白Anchor属性:......
  • DataGridView列填充实体类
    使用的地方:假如你有一个名为rgvProcessDtl的DataGridView控件DataTabledt=(DataTable)rgvProcessDtl.DataSource;foreach(DataRowrowindt){OG_ProcessGuidDtldtl=newOG_ProcessGuidDtl();FillModel(dtl,row);//将实体类对象与grid行填充}//////将数据填入实......
  • dataGridView控件和contextMenuStrip控件的结合使用
    效果展示: 0.在dataGridView控件中绑定 contextMenuStrip控件,设置ContextMenuStrip1. 设置 dataGridView选中类型为整行选中:SelectionMode:FullRowSelect不允许dataGridView一次能选择多个单元格:MultiSelect:Fale2.第二步再dataGridView控件中分别使用......
  • WPF-DataGrid 样式设置
    在wpf中使用DataGrid虽然方便,但是其默认样式往往很难满足需求,而修改模板往往由比较麻烦,很多时候我们会用ListBox或ListView+DataTemplate来实现同样效果,但为了有些时候需要应用,这里记录一下一些基本属性设置方法,以免忘记。code<Windowx:Class="WpfApp7.MainWindow"......
  • wpf datagrid绑定行选中状态
    样式如下<DataGridMargin="0,6,0,0"HeadersVisibility="All"RowHeaderWidth="60"HorizontalScrollBarVisibility="Visible"AutoGenerateColumns="False"ItemsSource="{BindingDispl......
  • WPF datagrid scrolldown and change the marked the location in canvas
    <Windowx:Class="WpfApp134.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft......
  • WPF DataGrid自动增长序号列
    ///<summary>///自动增长序号列///</summary>publicclassDataGridRowIndexColumn:DataGridTextColumn{///<summary>///可以指定开始序号///</summary>publicintStartIndex{get{return(int)GetValue(StartIndex......
  • Avalonia下DataGrid多选MVVM绑定的功能
    安装Avalonia.Xaml.BehaviorsInstall-PackageAvalonia.Xaml.BehaviorsDataGridSelectedItemsBehavior.csusingAvalonia;usingAvalonia.Controls;usingAvalonia.Threading;usingAvalonia.Xaml.Interactivity;namespaceCgdataBase;publicclassDataGridSelected......