将两个 UIElement 作为 CommandParameter 传递

Pass two UIElements as CommandParameter

我有一个 Prism MVVM 应用程序,可以轻松地将一个 UIElement 作为 CommandParameter 传递给 ViewModel 的 Command。但现在我想传递两个 UIElement。使用这个 XAML:

<Button.CommandParameter>
    <MultiBinding Converter="{StaticResource DummyMultiConverter}">
        <Binding ElementName="PasswordBoxType"/>
        <Binding ElementName="PasswordBoxRetype"/>
    </MultiBinding>
</Button.CommandParameter>

使用这个 Converter:

public class DummyMultiConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        return values;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

ViewModel 中的一个简单 DelegateCommand

private DelegateCommand<object> _commandCloseDialogOK;
public DelegateCommand<object> CommandCloseDialogOK =>
    _commandCloseDialogOK ??
    (_commandCloseDialogOK = new DelegateCommand<object>(commandParameter=> CommandCloseDialogOKExecute(commandParameter)));

public virtual void CommandCloseDialogOKExecute(object commandParameter)
{
    RaiseRequestClose(new DialogResult(ButtonResult.OK));
}

public virtual bool CanExecuteCommandCloseDialogOK()
{
    return true;
}

运行时 - Convert 方法正确获取 values,作为 2 PasswordBoxes 的数组。但是 CommandCloseDialogOKExecute 获取其 commandParameter 参数作为两个 nulls 的数组。如果我将 commandParameter 定义为 object[] 而不是 object,也会发生同样的情况。我应该怎么做 commandParameter 将是两个数组 PasswordBoxes?

首先,如果您使用的是 MVVM,您真的不应该将与视图相关的数据(如 UIElement 的)传递给视图模型。

假设您知道这一点并且这确实是一个简化的描述来说明您的问题,问题在于框架在 Convert returns 获取的值之前明确清除传递给 Convert 方法的数组应用于绑定。结果是它应用了现在为空的数组(空值):

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/System/Windows/Data/MultiBindingExpression.cs,1267

您可以通过在 Convert 方法中创建另一个数组来避免这种情况:

public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
    return new []{values[0], values[1]};
}