与 RelayCommand returns 未设置值的多重绑定

Multibinding with RelayCommand returns unset values

我有一个绑定到菜单项的命令,我想传递多个参数。我试过使用转换器,但它似乎 return 什么都没有。

我的转换器

public class AddConverter : IMultiValueConverter {
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        return values.Clone();
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
        throw new NotImplementedException();
    }
}

我的视图模型包含我的命令

class myViewModel: ViewModelBase {

private RelayCommand testCommand;

        public ICommand TestCommand {
            get {
                if (testCommand == null) {
                    testCommand = new RelayCommand((param) => test((object[])param));
                }
                return testCommand ;
            }
        }

        //Only trying to print out one of the params as a test
        public void test(object parameter) {
            var values = (object[])parameter;
            int num1 = Convert.ToInt32((string)values[0]);
            MessageBox.Show(num1.ToString());
        }

我对菜单项的绑定

//Using tags as a test
<ContextMenu>
    <MenuItem Name="testing" Header="Move to Position 10" Command="{Binding TestCommand}" Tag="7">
        <MenuItem.CommandParameter>
             <MultiBinding Converter="{StaticResource AddConverter}">
                 <Binding ElementName="testing" Path="Tag"/>
                 <Binding ElementName="testing" Path="Tag"/>
             </MultiBinding>
        </MenuItem.CommandParameter>
    </MenuItem>
</ContextMenu>

调试后,当我打开包含菜单项的 window 时,转换器启动,此时值对象为空。然后,当我 select 我的菜单项并触发命令时,当我执行时,参数为空。我不明白为什么我的转换器在我点击菜单项之前就关闭了,或者为什么值为空。

尝试用 RelativeSource 替换绑定的 ElementName。这对我有用:

<MenuItem Name="testing" Header="Move to Position 10" Command="{Binding TestCommand}" Tag="7">
    <MenuItem.CommandParameter>
        <MultiBinding Converter="{StaticResource AddConverter}">
            <Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
            <Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>
        </MultiBinding>
    </MenuItem.CommandParameter>
</MenuItem>

另请注意,您应该绑定到 TestCommand 属性 而不是 testCommand 字段。