开发者

WPF: ContextMenu item bound to a Command is enabled only after invoking the command from another source. Why does this be?

开发者 https://www.devze.com 2022-12-22 15:39 出处:网络
I have a ContextMenu whose items are all bound to commands and enable/disable correctly after ANY Command is invoked from another source but prior to, they are all disabled. So if I run the app, all t

I have a ContextMenu whose items are all bound to commands and enable/disable correctly after ANY Command is invoked from another source but prior to, they are all disabled. So if I run the app, all the MenuItems are disabled but if I invoke any of the bound commands from another source (buttons, for instance) they become synchronized with the 开发者_运维知识库CanExecute code. I have no idea how to debug this. Any thought would be helpful!?!


Seems to be a bug where there is no focused element in the window's main focus scope. A workaround is to bind MenuItem's CommandTarget to the main window.

Answer from Marco Zhou here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455

<Window.ContextMenu>
    <ContextMenu >
      <ContextMenu.Items>
        <MenuItem Command="ApplicationCommands.Open" 
                  CommandTarget="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/> 
      </ContextMenu.Items>
    </ContextMenu>
  </Window.ContextMenu>


Sometimes you need to force WPF to re-evaluate whether commands are enabled or not.

Somewhere in your code, add a call to:

CommandManager.InvalidateRequerySuggested();

See if that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号