要将动态命令参数传递给视图模型中的命令,您可以创建一个新类,例如DynamicCommandParameterValueConverter
:
/// <summary>
/// This class is inspired by MvvmCross MvxCommandParameterValueConverter,
/// but because we need dynamic command parameters, we need to implement our own combined with a CustomMvxWrappingCommand.
/// </summary>
/// <typeparam name="T">The type of the 'selected item' for the command</typeparam>
/// <typeparam name="TResult">The returned result that is used as input for the command.</typeparam>
public class DynamicCommandParameterValueConverter<T, TResult> : MvxValueConverter<ICommand, ICommand>
{
private readonly Func<T, TResult> commandParameterExpression;
public DynamicCommandParameterValueConverter(Func<T, TResult> commandParameterExpression)
{
this.commandParameterExpression = commandParameterExpression;
}
protected override ICommand Convert(ICommand value, Type targetType, object parameter, CultureInfo culture)
{
return new CustomMvxWrappingCommand<T, TResult>(value, commandParameterExpression);
}
}
CustomMvxWrappingCommand
接受一个作为参数,然后Func
被调用并传递给 commandsCanExecute/Execute
方法。以下是该类的一部分可能看起来像这样的片段:
public void Execute(object parameter)
{
if (wrapped == null)
{
return;
}
if (parameter != null)
{
Mvx.Warning("Non-null parameter overridden in MvxWrappingCommand");
}
wrapped.Execute(commandParameterOverride((T)parameter));
}
您可以修改MvxWrappingCommand
Mvx 中的类以实现上述示例。
全部使用:
set.Bind(myControl).For(control => control.ItemClick).To(vm => vm.MyCommand).WithConversion(
new DynamicCommandParameterValueConverter<MyModel, string>((MyModel item) =>
{
// Do custom logic before parsing the item..
}));