Search code examples
menuitem

WPF MenuItem style parameters not available on menu first open


I am specifying a context menu within the ControlTemplate of a TreeViewItem as follows:

                                    <ContextMenu ItemsSource="{Binding Commands}">
                                        <ContextMenu.ItemContainerStyle>
                                            <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}" />
                                            </Style>
                                        </ContextMenu.ItemContainerStyle>
                                    </ContextMenu>

where Commands is a list of ICommandViewModels objects with the following signature:

public interface ICommandViewModel 
    {
        string Name { get; }
        Image Icon { get; }
        ICommand Command { get; set; }
        object CommandParameter { get; set; }

    }

When the ContextMenu is open, CommandParamter being passed to Command is initially null, which disables Command as specified. If Command.CanExecute always return true, this is not a problem, as Command.Execute eventually gets the correct CommandParameter. In some cases, Command is not allowed to execute if CommandParamter is null, so this becomes a problem.

Anyone with a theory on what is going on here and a possible fix?

TIA.


Solution

  • Try swaping CommandParameter and Command property setters. I'm not sure about the reason of such behavior, but is looks like it doesn't requery can execute on CommandParameter changed. Another way is of fixing is described here https://web.archive.org/web/20140528012720/http://compositewpf.codeplex.com/discussions/47338

    Github issue tracking this exact issue here: https://github.com/dotnet/wpf/issues/3452