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

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


红糖糍粑
浏览 82回答 1
1回答

墨色风雨

尝试将ElementName绑定的 替换为RelativeSource. 这对我有用:<MenuItem Name="testing" Header="Move to Position 10" Command="{Binding TestCommand}" Tag="7">&nbsp; &nbsp; <MenuItem.CommandParameter>&nbsp; &nbsp; &nbsp; &nbsp; <MultiBinding Converter="{StaticResource AddConverter}">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <Binding Path="Tag" RelativeSource="{RelativeSource Self}"/>&nbsp; &nbsp; &nbsp; &nbsp; </MultiBinding>&nbsp; &nbsp; </MenuItem.CommandParameter></MenuItem>另请注意,您应该绑定到TestCommand属性而不是字段testCommand。
打开App,查看更多内容
随时随地看视频慕课网APP