在WPF中DelegateCommand的额外参数

时间:2017-07-22 19:03:29

标签: c# wpf delegates prism mef

我已经实现了Microsoft.Practices.Prism.Commands.DelegateCommand,如下所示,根据用户操作显示视图,但我想向OnExecute方法传递额外的参数。我需要FilterInfo对象,它可以帮助我在加载视图时过滤数据。但我不确定如何将FilterInfo对象传递给OnExecute

public class CustomCommand<T> : DelegateCommand<T>,ICommand
{
private string _commandName;
public CustomCommand(string _commandName, Action<T> executeMethod) : base(executeMethod)
        {
            this._commandName = _commandName;
        }
}

我已经定义了基本模块如下: -

public abstract class AbstractModuleBase : IModule
    {
      public List<CustomCommand> _customCommands = new List<CustomCommand>();

      protected void AddCustomCommand<TView>(string name, FilterInfo filterInfo=null)
        where TView : ViewModel
        {
            this._customCommands.Add(new CustomCommand<TView>(name, new Action<TView>(ModuleBase.OnExecute<TView>))
            {
                FilterInfo = filterInfo
            });
        }

        private static void OnExecute<TView>(TView obj)
        where TView : ViewModel
        {
          // Activate UI here.
          // Identified the view bashed on typeof(TView) and get it from MEF or IOC.
          // But here before calling the view i wanted to get FilterInfo obj.
        }
    }

我已将xaml定义如下

<ListBox ItemsSource="{Binding CustomCommandList}">
            <ListBox.ItemTemplate>
<DataTemplate >
               <Button Command="{Binding CustomCommand}"></Button>
</DataTemplate>     
</ListBox.ItemTemplate>
</ListBox>

以上自定义命令与ViewModel绑定。

[Export]
    public class DashViewModel
    {
        private ObservableCollection<CustomCommand> _CustomCommandList = AbstractModuleBase._customCommands;
    }
}   

在应用程序启动时,我调用下面的方法来命令注册视图: -

AbstractModuleBase.AddCustomCommand<DashViewModel>("Dash Name", new FilterInfo("Some Filter"));
AbstractModuleBase.AddCustomCommand<EmpViewModel>("Emp Name", new FilterInfo("Some Filter"));

1 个答案:

答案 0 :(得分:0)

以下是我在评论中建议的一个例子......

创建一个ICommand实现,将某些内容传递给参数,如草图:

public class FilterCommand : ICommand
{
    public FilterCommand( FilterInfo filterInfo )
    {
        _filterInfo = filterInfo;
    }

    #region ICommand
    public bool CanExecute( object parameter )
    {
        return true;
    }

    public void Execute( object parameter )
    {
        ((Action<FilterInfo>)parameter)( _filterInfo );
    }

    public event EventHandler CanExecuteChanged;
    #endregion

    #region private
    private readonly FilterInfo _filterInfo;
    #endregion
}

通过这种方式,您可以获得一个命令,您可以将您的方法(作为参数)传递给命令传递给您的方法(作为构造函数参数)。