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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.