WPF如何捕获ContextMenuClosing事件 [英] WPF How to catch ContextMenuClosing event
问题描述
我有以下XAML:
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<local:DropDownButton
HorizontalAlignment="Right"
Grid.Column="2"
Width="18"
Style="{StaticResource OrangeButton}"
ContextMenuClosing="colorPallete_ContextMenuClosing"
x:Name="btnSelectColor">
<Polygon Points="0,0,5,4,10,0" Fill="Black"/>
<local:DropDownButton.DropDown>
<ContextMenu StaysOpen="True" Name="colorPallete" ContextMenuClosing="colorPallete_ContextMenuClosing">
<MenuItem StaysOpenOnClick="True" OverridesDefaultStyle="True" ContextMenuClosing="colorPallete_ContextMenuClosing">
<MenuItem.Header>
<local:ColorPickerPopup x:Name="colorPicker" ContextMenuClosing="colorPallete_ContextMenuClosing"/>
</MenuItem.Header>
</MenuItem>
</ContextMenu>
</local:DropDownButton.DropDown>
</local:DropDownButton>
<Rectangle Width="17.5" Stroke="Black" Margin="0"
Fill="{DynamicResource CheckerBrush}"/>
<Rectangle Width="17.5" Margin="0" Name="rtcColorPreview" />
<TextBox Margin="2,0,0,0" Grid.Column="1"
Width="100" BorderThickness="0"
Text="{Binding ElementName=colorPicker, Mode=TwoWay, Path=SelectedColorName}"/>
</Grid>
标记为colrPallete的ContextMenu关闭时,不会调用事件处理程序colorPallete_ContextMenuClosing。我似乎无法弄清楚丢失了什么。
The event handler colorPallete_ContextMenuClosing is not being called when ContextMenu labelled colrPallete is closing. I cannot seem to figure out what is missing.
请帮助! TIA。
推荐答案
每个 MSDN文档 ...
ContextMenu本身是
FrameworkElement派生类,但ContextMenuClosing事件
不会由上下文菜单直接引发
。
相反,该事件是从拥有上下文菜单
作为属性的
元素引发的,并且仅当
a用户尝试关闭上下文
时才引发该事件
ContextMenu itself is a FrameworkElement derived class, but the ContextMenuClosing event will not be raised by a context menu directly. Instead, the event is raised from the element that "owns" the context menu as a property and is only raised when a user attempts to close a context menu in the UI.
您需要调整代码,以便仅在上定义处理程序完成操作后的DropDownButton
。如果存在嵌套的 ContextMenu
,则嵌套的 ContextMenu
显然会引发该事件。
You would need to adjust your code so that the handler is defined solely on the DropDownButton
as you have done. If there is a nested ContextMenu
then the nested ContextMenu
will obviously raise the event.
<local:DropDownButton ContextMenuClosing="colorPallete_ContextMenuClosing">
...
</local:DropDownButton>
使用按钮
...
<Button ContextMenuClosing="ContextMenu_ContextMenuClosing">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Go"/>
</ContextMenu>
</Button.ContextMenu>
</Button>
..当 ContextMenu
包含 MenuItem
关闭;
不确定所使用的 DropDownButton
控件是什么,所以我无法评论 DropDown
属性是什么以及如何嵌套 ContextMenu
。
Not certain what DropDownButton
control you are using so I can't comment on what the DropDown
property is and how you are nesting your ContextMenu
.
这篇关于WPF如何捕获ContextMenuClosing事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!