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


    第一步:在DataGrid中添加ContextMenu

    1. <DataGrid.ContextMenu>
    2. <ContextMenu>
    3. <MenuItem Header="删除选中项" Command="{Binding DeleteSelectedCommand}" />
    4. ContextMenu>
    5. DataGrid.ContextMenu>

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

    1. using GalaSoft.MvvmLight;
    2. using GalaSoft.MvvmLight.Command;
    3. using System.Collections.ObjectModel;
    4. namespace YourNamespace
    5. {
    6. public class MainViewModel : ViewModelBase
    7. {
    8. public MainViewModel()
    9. {
    10. Items = new ObservableCollection
    11. {
    12. new Item { Name = "Item 1" },
    13. new Item { Name = "Item 2" },
    14. new Item { Name = "Item 3" }
    15. };
    16. DeleteSelectedCommand = new RelayCommand(DeleteSelected, CanDeleteSelected);
    17. }
    18. public ObservableCollection<Item> Items { get; }
    19. public RelayCommand DeleteSelectedCommand { get; }
    20. private bool CanDeleteSelected()
    21. {
    22. return dataGrid?.SelectedItems.Count > 0;
    23. }
    24. private void DeleteSelected()
    25. {
    26. foreach (var selectedItem in dataGrid.SelectedItems.Cast().ToList())
    27. {
    28. Items.Remove(selectedItem);
    29. }
    30. }
    31. private DataGrid dataGrid;
    32. public void SetDataGrid(DataGrid grid)
    33. {
    34. dataGrid = grid;
    35. }
    36. }
    37. }

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

    1. public partial class MainWindow : Window
    2. {
    3. public MainWindow()
    4. {
    5. InitializeComponent();
    6. DataContext = new MainViewModel();
    7. (DataContext as MainViewModel)?.SetDataGrid(dataGrid);
    8. }
    9. }

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

            ViewModel中:设置好Command

            xaml的后端:将DataGrid传给ViewModel

  • 相关阅读:
    NumPy 均匀分布模拟及 Seaborn 可视化教程
    使用ResponseEntity实现文件下载
    【QT开发(1)】基于c++17的代码项目模板:QT build with Cmake
    【王道】计算机组成原理第三章存储系统(三)
    Vue的模板语法(下)
    rust的排序
    Xray是什么
    踩坑了,又踩坑了!
    Linux免交互
    树莓派4B配置ubuntu18.04.5
  • 原文地址:https://blog.csdn.net/weixin_46407807/article/details/132793052