WPF MenuItem style parameters not available on menu first open

末鹿安然 提交于 2020-01-17 03:49:25

问题


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.


回答1:


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 http://compositewpf.codeplex.com/Thread/View.aspx?ThreadId=47338



来源:https://stackoverflow.com/questions/3696926/wpf-menuitem-style-parameters-not-available-on-menu-first-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!