WPF中ContextMenu灰掉的解决方案

<Window x:Class="TestContextMenu.MainWindow"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Grid.ContextMenu>
<ContextMenu ItemsSource="{Binding Entities}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding Text}"/>
<Setter Property="Command" Value="{Binding ClickCommand}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Grid.ContextMenu>
<TextBlock Text="TestTest"/>
</Grid>
</Window>

这是通常的写法,看上去也没有任何问题,但是这样会有一个问题,就是右键菜单出来的时候,item都是灰色的,不可用,在网上找了很久,原因和解决方案如下,英语不好,就不翻译了

 

This is a known bug. If there is no focused element in the window's main focus scope, the CanExecute routing will stop at the ContextMenu, so it will not reach to the CommandBinding on the Window, one workaround is to bind MenuItem's CommandTarget to the main window.

 

将代码修改如下就可以解决这个问题了(斜体部分就是workaround):

 

<Window x:Class="TestContextMenu.MainWindow"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid>
<Grid.ContextMenu>
<ContextMenu ItemsSource="{Binding Entities}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding Text}"/>
<Setter Property="Command" Value="{Binding ClickCommand}"/>
<Setter Property="CommandTarget" Value="{Binding Path=PlacementTarget,RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Grid.ContextMenu>
<TextBlock Text="TestTest"/>
</Grid>
</Window>


That's all.

点击下载Sample 

参考:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7bd75a7c-eab4-4f3a-967b-94a9534a7455/

转载于:https://www.cnblogs.com/liuxun/archive/2011/11/01/2232219.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值