具有 MVVM 的 DataGrid 的 WPF selectAll/unselectAll 行

WPF selectAll/unselectAll rows of a DataGrid with MVVM

我有一个 WPF DataGrid,ItemsSource 属性 绑定到视图模型。 单击 Button 时,一个方法正在对 DataGrid 的选定行进行处理。 工作完成后,我想从视图模型中取消选择 DataGrid 的所有行,如何以 MVVM 方式实现此目的?

XAML :

<DataGrid AutoGenerateColumns="False"
     ItemsSource="{Binding ObCol_View}"
     SelectedItem="{Binding SelectedItem}

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <GalaCmd:EventToCommand Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding SelectedItems, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</DataGrid>

<Button Content="Apply" Command="{Binding PerformCommand}"/>

视图模型

public class ViewModelprices_manager<T> : WindowViewModel
{
    public ViewModelprices_manager()
    {
        SelectionChangedCommand = new RelayCommand<IList>
        (items =>
            {
                SelectedItems = items;
            }
        );

        myObCol_View = new ObservableCollection<View_prices_manager<T>>();
    }

    public IList SelectedItems { get; set; }

    private readonly ObservableCollection<View_prices_manager<T>> myObCol_View;
    public ObservableCollection<View_prices_manager<T>> ObCol_View_Parametric { get { return myObCol_View; } }

    public RelayCommand<IList> SelectionChangedCommand
    {
        get;
        private set;
    }

    private RelayCommand myPerformCommand;

    public RelayCommand PerformCommand
    {
        get
        {
            if (myPerformCommand == null)
                myPerformCommand = new RelayCommand(PerformCommandAction);

            return myPerformCommand;
        }
    }

    private void PerformCommandAction()
    {
        perform();
    }

    public void perform()
    {
        foreach (View_prices_manager<T> item in SelectedItems)
        {
            item.Price *= ratio;
        }

        //DataGrid.UnselectAll <-- Here I want to unselect all to reset the selection in SelectedItems
    }
}

以 MVVM 方式清除选择。

绑定到 SelectedItem 属性 到视图模型:

<DataGrid SelectedItem="{Binding SelectedItem, Mode=TwoWay}">

并在您的代码中将 SelectItem 设置为 null

viewModel.SelectItem = null;

当然,您的 viewModel class 必须正确实施 INotifyPropertyChanged

The topic is reopened, I would like to see your solution

一个简化的例子。
如果您需要任何其他详细信息,请写下哪些,我会添加或解释它们。

示例使用 BaseInpc and RelayCommand classes.

Collection 项目 class:

using Simplified;

namespace ClearSelectedItems
{
    public class Product : BaseInpc
    {
        private string _title;
        private decimal _price;

        public string Title { get => _title; set => Set(ref _title, value); }
        public decimal Price { get => _price; set => Set(ref _price, value); }
    }
}

ViewModel:

using Simplified;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;

namespace ClearSelectedItems
{
    public class ProductsViewModel
    {
        public IList SelectedProducts{ get; set; }

        public decimal Ratio { get; set; }

        private ICommand _performCommand;
        public ICommand PerformCommand => _performCommand
            ?? (_performCommand = new RelayCommand(PerformExecute));

        private void PerformExecute(object parameter)
        {
            foreach (var product in SelectedProducts.Cast<Product>())
            {
                product.Price *= Ratio;
            }

            // Clearing selection
            SelectedProducts.Clear();
        }

        // An example of filling a collection
        public List<Product> Products { get; }
            = new List<Product>()
            {
                new Product() { Title = "IPhone", Price=1500},
                new Product() { Title = "Samsung", Price=1200},
                new Product() { Title = "Nokia", Price=1000},
                new Product() { Title = "LG", Price=500}
           };
    }
}

Class 个静态处理程序。 为简单起见,以免创建行为。

using System;
using System.Windows.Controls.Primitives;

namespace ClearSelectedItems
{
    public static class Handlers
    {
        public static EventHandler OnDataGridInitialized { get; } = (sender, e) =>
        {
            MultiSelector selector = (MultiSelector)sender;
            ProductsViewModel viewModel = (ProductsViewModel)selector.DataContext;
            viewModel.SelectedProducts = selector.SelectedItems;
        };
    }
}

Window XAML:

<Window x:Class="ClearSelectedItems.ExampleWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ClearSelectedItems"
        mc:Ignorable="d"
        Title="ExampleWindow" Height="450" Width="400">
    <Window.DataContext>
        <local:ProductsViewModel/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding Products}"
                  Initialized="{x:Static local:Handlers.OnDataGridInitialized}"/>
        
        <TextBox Text="{Binding Ratio}" VerticalAlignment="Bottom" HorizontalAlignment="Left" 
                 MinWidth="100" Margin="5" Padding="15 5"/>
        
        <Button Content="Apply Ratio" Command="{Binding PerformCommand}"
                Margin="5" Padding="15 5"
                HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
    </Grid>
</Window>