ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

WPF中ContextMenu灰掉的解决方案

2019-08-21 13:39:57  阅读:369  来源: 互联网

标签:http ContextMenu xaml 2006 Loaded WPF 灰掉 com microsoft


原文链接: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

标签:http,ContextMenu,xaml,2006,Loaded,WPF,灰掉,com,microsoft
来源: https://blog.csdn.net/weixin_30613727/article/details/99954194

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有