gpt4 book ai didi

c# - 如何在 WPF 中使用 ContextMenu UserControl?

转载 作者:太空狗 更新时间:2023-10-29 22:23:42 25 4
gpt4 key购买 nike

我有一个这样的用户控件:

<UserControl x:Class="MyApp.UserControls.MyContextMenu"
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"
mc:Ignorable="d"
ContextMenuOpening="OnContextMenuOpening"
d:DesignHeight="300" d:DesignWidth="300">

<UserControl.ContextMenu>
<ContextMenu>
...
</ContextMenu>
</UserControl.ContextMenu>
</UserControl>

我的问题是:如何将上下文菜单用于数据网格之类的内容:

<DataGrid ContextMenu="{usercontrols:MyContextMenu}"

不幸的是,这不起作用,因为指定的值不正确,需要一个 ContextMenu

注意:我需要在几个地方重复使用我的上下文菜单,所以我把它放在了自己的文件中。此外,我需要能够收听 OnContextMenuOpening 事件,因为打开时的菜单需要做一些关于菜单的工作,并且遗憾的是不会为上下文菜单触发事件:http://connect.microsoft.com/VisualStudio/feedback/details/353112/contextmenu-opening-event-doesnt-fire-properly

"ContextMenu itself is a FrameworkElement derived class, but this event will not be raised from the context menu being opened as a source. The event is raised from the element that "owns" the context menu as a property and is only raised when a user attempts to open a context menu in the UI."

这个事件问题是我为用户控件放置菜单的原因——这样用户控件就可以获取事件并完成工作。

更新:我尝试将其作为根元素并扩展上下文菜单:

enter image description here

和代码隐藏:

enter image description here

但我得到:ContextMenu 不能有逻辑或可视父级

最佳答案

无论您如何调用 UserControl,它都不是上下文菜单。您必须从 ContextMenu 派生而不是用户控件:

<ContextMenu x:Class="MyApp.MyContextMenu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<MenuItem Header="Item 1"/>
<MenuItem Header="Item 2"/>
...
</ContextMenu>

public partial class MyContextMenu : ContextMenu
{
public MyContextMenu()
{
InitializeComponent();
}
}

但是你为什么要这么做呢?

关于c# - 如何在 WPF 中使用 ContextMenu UserControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10635382/

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