c# - 使用 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>
调试后,当我打开包含菜单项的窗口时,转换器将启动,此时值对象为空。然后,当我选择我的菜单项并触发命令时,当我执行时,参数为空。我不明白为什么我的转换器在我点击菜单项之前就启动了,或者为什么这些值为空。
解决方案
尝试将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
字段。
推荐阅读
- android - 加载资源失败:服务器响应状态为 400 () Ionic 3 android
- css - 单击时设置 css 样式并在单击时删除它们
- java - 春季数据更新并发读取
- database - Oracle:加入 2 个结果集
- gridview - Flutter:在 GridView 的平铺中使用 GestureDetector 进行点击延迟
- php - google api,具有指定标签的共享联系人
- applescript - Apple脚本将系统偏好设置窗格置于前面
- php - 如何在 x-mailer 中添加附件?
- keycloak - Keycloak:我可以在决定阻止用户时考虑帐户 IP 地址吗?
- git - 进行全局设置时,Git 不会在 HOME 目录中查找 .gitconfig