[WPF]XAML中使用IMultiValueConverter實(shí)現(xiàn)Command的多參數(shù)傳參
問題
如何對(duì)ICommand傳入多個(gè)參數(shù)?
背景
最近在做一個(gè)WPF的開發(fā),有多個(gè)相近的功能寫了不同的Command,因?yàn)橐獙?duì)應(yīng)不同的對(duì)象。因?yàn)槭荂trlCV,顯得代碼有點(diǎn)冗贅不夠優(yōu)雅,但是ICommand又只能接受一個(gè)參數(shù)。
思路
使用MultiBinding,對(duì)CommandParameter進(jìn)行綁定,然后再使用IMultiValueConverter對(duì)多個(gè)參數(shù)進(jìn)行轉(zhuǎn)換,變成object傳進(jìn)去
代碼實(shí)現(xiàn)
- 實(shí)現(xiàn)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);
//要重新創(chuàng)建values的實(shí)例,否則參數(shù)傳過去是空引用
return args;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
- 在XAML里實(shí)現(xiàn)綁定
<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進(jìn)行傳參
僅展示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();
}
}

浙公網(wǎng)安備 33010602011771號(hào)