gpt4 book ai didi

c# - ContextMenuOpening 事件未在 WPF 中触发?

转载 作者:可可西里 更新时间:2023-11-01 08:13:56 24 4
gpt4 key购买 nike

我有一个资源字典,里面有一个上下文菜单:

<ResourceDictionary x:Class="MyApp.Components.MyContextMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyApp"
xmlns:components="clr-namespace:MyApp.Components">
<ContextMenu ContextMenuOpening="OnContextMenuOpening">

资源字典 XAML 背后有这段代码:

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

namespace MyApp.Components
{
public partial class MyContextMenu : ResourceDictionary
{
public MyContextMenu()
{
InitializeComponent();
}

void OnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
Console.WriteLine("here i am!");
}
}
}

日志没有出现。我想知道为什么事件没有触发或到达正确的位置 - 问题是因为我将上下文菜单包装在这个资源字典中吗?

更新:有趣的是,如果我删除代码隐藏函数,我会在编译期间遇到错误:

does not contain a definition for 'ContextMenu_OnContextMenuOpening' and no extension method 'ContextMenu_OnContextMenuOpening' accepting a first argument of type 'MyApp.Components.MyContextMenu' could be found (are you missing a using directive or an assembly reference?)

更新 2: 看起来 Console.WriteLineDebug.WriteLine 都会产生输出,但只是“随机”产生输出,尤其是当我' 在项目底部附近单击。某种碰撞检测可能不起作用?

最佳答案

ContextMenuOpening 事件必须在 ContextMenu 的祖先而不是 ContextMenu 本身上处理。如果您尝试在 ContextMenu 上处理它,则只有当您在 ContextMenu 已经打开时右键单击时才会触发该事件。

关于c# - ContextMenuOpening 事件未在 WPF 中触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10622511/

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