WPF Command绑定并传参(以DataGrid示例)

一、问题场景:

  使用WPF的DataGrid来展示表格数据,想要批量删除或者导出数据行时,由于SelectedItems属性不支持MVVM的方式绑定(该属性是只读属性),所以可以通过命令参数的方式将该属性值传给命令,即利用CommandParameter将SelectedItems传递给删除或导出命令。

二、使用方式:

1.xaml部分

<DataGrid x:Name="dtgResult" ItemsSource="{Binding ResultInfo}" CanUserSortColumns="True" Height="205" Width="866" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="患者ID" Binding="{Binding PatientId}" MinWidth="46" IsReadOnly="True"/>
        <DataGridTextColumn Header="姓名" Binding="{Binding PatientName}" MinWidth="46" IsReadOnly="True"/>
        <DataGridTextColumn Header="性别" Binding="{Binding PatientGender}" MinWidth="46" IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>
<Button x:Name="btnResultDel" Content="删除" Command="{Binding ResultDeleteCommand}" CommandParameter="{Binding SelectedItems,ElementName=dtgResult}"/>

2.C#部分

private RelayCommand _deleteCommand;
public ICommand ResultDeleteCommand {
  get
  {
    
if (_deleteCommand == null)     {
      _deleteCommand
= new RelayCommand(param =>On_Delete_Command_Excuted(param));     }   return _deleteCommand;   } } private void On_Delete_Command_Excuted(Object param) {

}

每次触发ResultDeleteCommand,都会把控件dtgResult的SelectedItems属性值作为参数param传递给On_Delete_Command_Excuted方法。

三、Tip

1.如何把Object类型的参数转成List<T>呢? (其中T是DataGrid中每条数据的类型)

System.Collections.IList items = (System.Collections.IList)param;
var collection = items.Cast<T>();
var selectedItems = collection.ToList();

其中selectedItems就是用户在DataGrid界面选中的多条数据行。

2.RelayCommand

/// <summary>
/// A command whose sole purpose is to relay its functionality to other objects by invoking delegates. The default return value for the CanExecute method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;        

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute): this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
         if (execute == null)
            throw new ArgumentNullException("execute");
_execute
= execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute == null ? true : _canExecute(parameter); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { _execute(parameter); } }

 

posted @ 2022-01-06 10:36  LXLR  阅读(3008)  评论(1编辑  收藏  举报