w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
WPF : MenuItem.CommandParameter binding set to null

This is apparently a known problem with the CommandParameter binding.

Since I did not want to edit Prism code, I ended up using the CommandParameterBehavior class defined in the referenced CodePlex post.

Modifying my custom RelayCommand class to implement IDelegateCommand as follows:

 public class RelayCommand : IDelegateCommand
{
    readonly protected Predicate<object> _canExecute;
    readonly protected Action<object> _execute;      

    public RelayCommand(Predicate<object> canExecute,
Action<object> execute)
    {
        _canExecute = canExecute;
        _execute = execute;          
    }

    public void RaiseCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, EventArgs.Empty);
    }      

    public virtual bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged;

    public virtual void Execute(object parameter)
    {
        _execute(parameter);
    }      
}

and modifying my original style to use the CommandParameterBehavior like so:

 <Style TargetType="MenuItem">
                <Setter Property="Command" Value="{Binding Command}"
/>
                <Setter Property="CommandParameter" Value="{Binding
CommandParameter}" />
                <Setter Property="Header" Value="{Binding Name}" />
                <Setter Property="Icon" Value="{Binding Icon}" />
                <Setter
Property="utility:CommandParameterBehavior.IsCommandRequeriedOnChange"
Value="true"
            </Style>

The CommandParameter is now passed correctly.





© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.