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# SIMD向量索引实战:从理论到高性能实现
c#
c#上位机2 小时前
wpf之TabControl
c#·wpf
mingupup2 小时前
WPF应用最小化到系统托盘
wpf
玩泥巴的3 小时前
打造.NET平台的Lombok:实现构造函数注入、日志注入、构造者模式代码生成等功能
c#·.net·代码生成·roslyn
张人玉11 小时前
C# TCP 客户端开发笔记(TcpClient)
笔记·tcp/ip·c#
张人玉14 小时前
C# 通讯关键类的API
开发语言·c#
qiangshang99012617 小时前
WPF+MVVM入门学习
学习·wpf
DASXSDW17 小时前
Abp vNext-事件总线使用实现及解析
ui·wpf
纸照片17 小时前
【邪修玩法】如何在WPF中开放 RESTful API 服务
后端·wpf·restful
啊丢_20 小时前
WPF基本布局容器与控件
wpf