对ICommand进行多参数传参
问题
如何对ICommand传入多个参数?
背景
最近在做一个WPF的开发,有多个相近的功能写了不同的Command,因为要对应不同的对象。因为是CtrlCV,显得代码有点冗赘不够优雅,但是ICommand又只能接受一个参数。
思路
使用MultiBinding,对CommandParameter进行绑定,然后再使用IMultiValueConverter对多个参数进行转换,变成object传进去
代码实现
- 实现IMultiValueConverter
public class MultiValueConverter:IMultiValueConverter{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
object[] args = new object[values.Length];
values.CopyTo(args, 0);
//要重新创建values的实例,否则参数传过去是空引用
return args;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
- 在XAML里实现绑定
<Page.Resource>
<cvt:MultiValueConverter x:Key="commandParameterConverter">
</Page.Resource>
...
<Button
Command="{Binding StartCommand}"
Content="Start">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource commandParameterConverter}">
<Binding Path="DataContext.Path1" RelativeSource="{RelativeSource AncestorType=local:HomePage}" />
</MultiBinding>
</Button.CommandParameter>
</Button>
- 在ViewModel中的处理逻辑
public class HomePageViewModel:ObservableObject{
public string Path1 {get;set;}
[RelayCommand]
private async Task Start(object arg){
if(object is not object[] args || args[0] is not string path){
throw new Exception("Invalid argument type");
}
//Do Something else...
}
}
- 亦可以使用Tuple进行传参
仅展示TupleConverter啦,其余大体差不多
public class TupleConverter:IMultiValueConverter{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return Tuple.Create(values[0],values[1],values[2]);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
标签:传参,args,XAML,object,IMultiValueConverter,values,参数,public
From: https://www.cnblogs.com/echo-sama/p/18414343