WPF中ContextMenu灰掉的解决方案

原文链接:http://www.cnblogs.com/liuxun/archive/2011/11/01/2232219.html
<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

上一篇:UWP实现吸顶的Pivot


下一篇:android – 如何在Activity可见后运行我的代码?