首页 > 解决方案 > 使用 RelayCommand 进行多重绑定返回未设置的值

问题描述

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

我的转换器

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>

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

标签: c#wpfmultibindingrelaycommand

解决方案


尝试将ElementName绑定替换为RelativeSource. 这对我有用:

<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>

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


推荐阅读