0

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?

Matthew
  • 28,056
  • 26
  • 104
  • 170

1 Answers1

4

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

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • 1
    The second link appears to the same problem that I am having. It appears it is a bug in WPF itself. I was able to work around the issue by returning `false` when `commandParameter` is `null`, but your mileage may vary. – Matthew Oct 08 '11 at 18:08
  • Yeah. It's a bug. I reduced my problem to just a list of buttons. It worked so I stared building up the original page around that list. I built it up completely and now it works. It is the exact same XAML character for character as the original view. This is most certainly a bug. I wish I had reproducible proof I would report it. These are the types of bugs that never get fixed. – Jordan Sep 15 '15 at 15:09