mvvm框架下对wpf的DataGrid多选,右键操作

第一步:在DataGrid中添加ContextMenu

XML 复制代码
        <DataGrid.ContextMenu>
            <ContextMenu>
                <MenuItem Header="删除选中项" Command="{Binding DeleteSelectedCommand}" />
            </ContextMenu>
        </DataGrid.ContextMenu>

第二步:在ViewModel中创建一个命令(DeleteSelectedCommand)来处理删除选中项的逻辑。确保为ViewModel设置了DataContext。其中Items就是DataGrid中每行的对象集合

cs 复制代码
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System.Collections.ObjectModel;

namespace YourNamespace
{
    public class MainViewModel : ViewModelBase
    {
        public MainViewModel()
        {
            Items = new ObservableCollection<Item>
            {
                new Item { Name = "Item 1" },
                new Item { Name = "Item 2" },
                new Item { Name = "Item 3" }
            };

            DeleteSelectedCommand = new RelayCommand(DeleteSelected, CanDeleteSelected);
        }

        public ObservableCollection<Item> Items { get; }

        public RelayCommand DeleteSelectedCommand { get; }

        private bool CanDeleteSelected()
        {
            return dataGrid?.SelectedItems.Count > 0;
        }

        private void DeleteSelected()
        {
            foreach (var selectedItem in dataGrid.SelectedItems.Cast<Item>().ToList())
            {
                Items.Remove(selectedItem);
            }
        }

        private DataGrid dataGrid;

        public void SetDataGrid(DataGrid grid)
        {
            dataGrid = grid;
        }
    }
}

第三步:在MainWindow.xaml.cs中设置DataContext和DataGrid的关联:

cs 复制代码
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
        (DataContext as MainViewModel)?.SetDataGrid(dataGrid);
    }
}

总结:xaml中:对DataGrid添加ContextMenu并绑定Command

ViewModel中:设置好Command

xaml的后端:将DataGrid传给ViewModel

相关推荐
昏睡红猹1 小时前
C#脚本化(Roslyn):如何在运行时引入nuget包
c#
张人玉2 小时前
C# 常量与变量
java·算法·c#
就是有点傻2 小时前
在C#中,可以不实例化一个类而直接调用其静态字段
c#
软件黑马王子2 小时前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon3 小时前
C#读写文件:多种方式详解
开发语言·数据库·c#
就是有点傻4 小时前
C#如何实现中英文快速切换
数据库·c#
一名用户8 小时前
unity实现梦日记式传送组件
后端·c#·unity3d
阿蒙Amon9 小时前
C#扩展方法全解析:给现有类型插上翅膀的魔法
开发语言·c#
qq_3923971220 小时前
Redis常用操作
数据库·redis·wpf
三千道应用题1 天前
WPF学习笔记(25)MVVM框架与项目实例
wpf