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

相关推荐
csdn_aspnet4 小时前
C# 求n边凸多边形的对角线数量(Find number of diagonals in n sided convex polygon)
开发语言·算法·c#
会飞的大可6 小时前
Spring Cloud Alibaba全景:Nacos、Sentinel、Seata整合实战
sentinel·wpf
武藤一雄8 小时前
C# 设计模式大全(第一弹|7种)
microsoft·设计模式·微软·c#·.net·.netcore
格林威9 小时前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
向上的车轮10 小时前
熟悉C#如何转TypeScript——SDK与包引用
开发语言·typescript·c#
baivfhpwxf202311 小时前
DataGrid 中增加选择列 功能实现
ui·wpf
CSharp精选营12 小时前
Dispose 不释放?C# 资源泄漏的 3 种隐蔽场景排查
c#·资源泄漏
unicrom_深圳市由你创科技13 小时前
LabVIEW和C#在工业控制中的应用差异是什么?
fpga开发·c#·labview
唐青枫14 小时前
C#.NET Consul + Steeltoe 深入解析:服务注册发现、健康检查与微服务接入
c#·.net
czhc114007566314 小时前
winform 330 跨线程 异步
wpf·线程·winform