为什么我的 CommandParameter 有时(但并非总是)为 null,尽管已在标记中声明?
我的代码大致如下:
<MenuItem Header="Do Something"
Command="{Binding ChangeSomeEnumValue}"
CommandParameter="{x:Static someNamespace:SomeEnum.EnumValue}" />
在用作 DataContext 的视图模型中:
// RelayCommand takes an Action<object> to be used by Execute, and a
// Predicate<object> to be used by CanExecute.
this.ChangeSomeEnumValue = new RelayCommand(
p => this.CurrentEnumValue = (SomeEnum)p,
ChangeSomeEnumValuePredicate);
...
bool ChangeSomeEnumValuePredicate(object commandParameter)
{
Console.WriteLine(commandParameter);
var enumValue = (SomeEnum)commandParameter;
...
return true;
}
首次显示 MenuItem
时,输出为:
EnumValue
EnumValue
EnumValue
当我单击 MenuItem
时“EnumValue " 又打印了 3 次,然后我在 var enumValue = (SomeEnum)commandParameter
行上得到一个 NullReferenceException
(commandParameter
is 无效的)。
我想不出为什么 CommandParameter
在调用 CanExecute
的前几次是正确的,但是 null
另一个时间。这是怎么回事?
I have code that looks roughly like this:
<MenuItem Header="Do Something"
Command="{Binding ChangeSomeEnumValue}"
CommandParameter="{x:Static someNamespace:SomeEnum.EnumValue}" />
In the viewmodel used as the DataContext:
// RelayCommand takes an Action<object> to be used by Execute, and a
// Predicate<object> to be used by CanExecute.
this.ChangeSomeEnumValue = new RelayCommand(
p => this.CurrentEnumValue = (SomeEnum)p,
ChangeSomeEnumValuePredicate);
...
bool ChangeSomeEnumValuePredicate(object commandParameter)
{
Console.WriteLine(commandParameter);
var enumValue = (SomeEnum)commandParameter;
...
return true;
}
When the MenuItem
is first displayed, the output is:
EnumValue
EnumValue
EnumValue
When I click on the MenuItem
"EnumValue" is printed 3 more times, then I get a NullReferenceException
on the line var enumValue = (SomeEnum)commandParameter
(commandParameter
is null).
I can't for the life of me think of a reason why CommandParameter
would be correct the first several times CanExecute
is called, but null
another time. What is going on here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我遇到过上下文菜单的命令谓词函数存在一些问题。这可能会帮助你 -
第一次调用 CanExecute 时 WPF CommandParameter 为 NULL
<一个href="https://stackoverflow.com/questions/3027224/icommand-canexecute-being-passed-null-even-though-commandparameter-is-set">即使设置了 CommandParameter,ICommand.CanExecute 仍传递 null
There have been some issue with Context Menu's Commands predicate function which i have faced. This might help you out -
WPF CommandParameter is NULL first time CanExecute is called
ICommand.CanExecute being passed null even though CommandParameter is set