gpt4 book ai didi

c# - 如何在 WPF 中订阅上下文菜单关闭事件?

转载 作者:行者123 更新时间:2023-12-03 19:40:59 26 4
gpt4 key购买 nike

我尝试了各种解决方案,例如发现的 here ,其接受的答案如下:

<Button ContextMenuClosing="ContextMenu_ContextMenuClosing">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header="Go"/>
</ContextMenu>
</Button.ContextMenu>
</Button>

但是,在实现上述解决方案后,我仍然无法成功监听 ContextMenuClosing 事件,无论它如何关闭(进行选择、单击父按钮、单击菜单或按钮外的任何位置)。下面是我的代码,我做错了什么?

测试页.xaml

<Page x:Class="MyProject.pages.TestPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MIMOUI.pages"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
Title="TestPage">

<Grid>
<Button x:Name="myMenuButton"
Width="140"
Height="100"
Click="myMenuButton_Click"
ContextMenuClosing="myMenuButton_ContextMenuClosing"
Background="NavajoWhite"
Foreground="BurlyWood">

<Button.ContextMenu>
<ContextMenu x:Name="myMenuButton_ContextMenu" Width="250">
<MenuItem x:Name="myTaskMenuButton" Header="TASKS" />
<MenuItem x:Name="myTransactionButton" Header="TRANSACTION" />
<MenuItem x:Name="mySetupMenuButton" Header="SETUP" />
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
</Page>

TestPage.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;

namespace MyProject.pages {
public partial class TestPage : Page {
public TestPage() {
InitializeComponent();
}

public void myMenuButton_Click(object sender, RoutedEventArgs e) {
(sender as Button).ContextMenu.IsOpen = true;
}

public void myMenuButton_ContextMenuClosing(object sender, RoutedEventArgs e) {
Console.WriteLine("intercepted!!!!");
e.Handled = true;
}
}
}

最佳答案

出于我未知的原因,当您的 Click 代码打开它时,ContextMenuClosing 似乎不会被触发。如果您通过右键单击按钮打开ContextMenu,则会按预期触发事件。作为解决方法,您可以使用 ContextMenu.Closed似乎在这两种情况下都调用了事件

<Button x:Name="myMenuButton" Click="myMenuButton_Click" ...>
<Button.ContextMenu>
<ContextMenu ... Closed="myMenuButton_ContextMenu_Closed">
<MenuItem x:Name="myTaskMenuButton" Header="TASKS" />
<MenuItem x:Name="myTransactionButton" Header="TRANSACTION" />
<MenuItem x:Name="mySetupMenuButton" Header="SETUP" />
</ContextMenu>
</Button.ContextMenu>
</Button>

并在您的代码中

private void myMenuButton_ContextMenu_Closed(object sender, RoutedEventArgs e)
{
Debug.WriteLine("myMenuButton_ContextMenu_Closed");
}

唯一的区别似乎是您无法像在 ContextMenuClosing 事件中那样阻止 ContextMenu 关闭

关于c# - 如何在 WPF 中订阅上下文菜单关闭事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36223529/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com