如何在WPF DataGrid上获得多个SelectedItem(行)

问题描述 投票:-1回答:1

如何在WPF DataGrid上获取多个选定项(行)?

我只能使用SelectedItem属性获得一个选定的项目。

XAML:

<Window x:Class="WpfDataGridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <DataGrid ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem}">
        </DataGrid>
    </Grid>
</Window>

ViewModel:

  public class MainViewModel
  {
    public MainViewModel(IEnumerable<Customer> customers)
    {
      Items = new ObservableCollection<Customer>(customers);
    }

    public ObservableCollection<Customer> Items { get; }

    public Customer SelectedItem { get; set; }
  }


如果我选择几行,则SelectedItem保持不变。如何获得多个所选项目?

c# wpf mvvm
1个回答
0
投票
  1. 使用nuget依赖MvvmLight
  2. 使用SelectionChanged事件处理程序,并将SelectedItems发送到VM(感谢https://stackoverflow.com/users/2289942/nawed-nabi-zada

请参见下面的代码

XAML:

<Window x:Class="WpfDataGridTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <Grid>
        <DataGrid ItemsSource="{Binding Items}"
                  SelectedItem="{Binding SelectedItem}"
                  Name="grid">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <i:InvokeCommandAction Command="{Binding SelectionChangedCommand}" 
                                           CommandParameter="{Binding SelectedItems, ElementName=grid}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </DataGrid>
    </Grid>
</Window>

ViewModel:

  public class MainViewModel
  {
    public MainViewModel(IEnumerable<Customer> customers)
    {
      Items = new ObservableCollection<Customer>(customers);
    }

    public ObservableCollection<Customer> Items { get; }

    public Customer SelectedItem { get; set; }

    public ICommand SelectionChangedCommand => _selectionChangedCommand ?? (_selectionChangedCommand = new RelayCommand<IList>(OnChanged));

    private void OnChanged(IList dataset)
    {
      var selectedItems = dataset.OfType<Customer>();
    }

    private ICommand _selectionChangedCommand;
  }
© www.soinside.com 2019 - 2024. All rights reserved.