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

相关推荐
点心的游戏开发世界8 小时前
Unity C# 脚本学习笔记:命名空间与 using
学习·unity·c#
淡海水10 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
点心的游戏开发世界10 小时前
Unity C# 脚本学习笔记:泛型
学习·unity·c#
公子小六14 小时前
基于.NET的Windows窗体编程之WinForms滑块与上下控件
windows·microsoft·c#·.net·winforms
曹牧14 小时前
C#:文本文件读取
服务器·前端·c#
2601_9673387115 小时前
C#上位机开发零基础入门到精通全套视频
开发语言·c#
czhc114007566320 小时前
2026-09-03 博客:配置与密码 · 合并代码 · 超时排查
c#
格林威1 天前
C#图像夜间识别率提升:使用OpenCvSharp和Halcon融合DeepSORT实现复杂场景下准确识别
开发语言·人工智能·数码相机·机器学习·计算机视觉·c#·视觉检测
dalong101 天前
WPF:箭头绘制程序
wpf·自定义绘制
曹牧1 天前
C#:线程间操作无效,不是从创建控件线程访问
开发语言·c#