我有一个命令绑定到我拥有的菜单项,我想传递多个参数。我尝试过使用转换器,但它似乎没有返回任何内容。我的转换器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>调试后,当我打开包含菜单项的窗口时,转换器会启动,此时值对象为空。然后,当我选择菜单项并触发命令时,当我开始执行时,参数为空。我不明白为什么我的转换器在我单击菜单项之前就启动了,或者为什么这些值为空。
1 回答
墨色风雨
TA贡献1853条经验 获得超6个赞
尝试将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>
另请注意,您应该绑定到TestCommand属性而不是字段testCommand。
- 1 回答
- 0 关注
- 107 浏览
添加回答
举报
0/150
提交
取消