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

相关推荐
雪隐15 小时前
WPF + MVVM 实战系列01-一个老狗回炉重造 WPF 的 12 天血泪史
sqlite·c#·mvvm
在世修行16 小时前
从零打造 C# 工业视觉检测系统(四):海康威视 MVS SDK 入门与相机枚举实战
数码相机·c#·视觉检测
神秘的MT17 小时前
C# WinForm Socket 服务器 + 串口转发
服务器·网络·学习·c#
aGdF8E3gQ18 小时前
【Application Insights】采样率对Function App日志收集的影响和解决方法
python·flask·wpf
czhc114007566321 小时前
8.4:今日概念与语法总结
c#
大数据张老师21 小时前
Typora 导出 Word 模版操作手册
开发语言·c#·word·typora
我是苏苏1 天前
C#基础:使用System.Speech.Synthesis离线播放/朗读文字内容
开发语言·c#
程序员-Benothing1 天前
如何实现高并发系统订单30分钟自动关闭?
开发语言·c#·wpf
海盗12342 天前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
一水2 天前
Redis实战:一个AI工作流系统里的五个应用场景,从传参到限流的完整链路
数据库·redis·wpf