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