gpt4 book ai didi

c# - WPF 上下文菜单 = {x :Null} but still shows menu inside ContentControl

转载 作者:太空狗 更新时间:2023-10-29 20:27:24 29 4
gpt4 key购买 nike

我需要禁用 TextBox 的标准上下文菜单。我创建了一个新的 WPF 项目并添加了以下内容:

<Window x:Class="WpfApplication3.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">
<Grid>
<ContentControl>
<ContentControl.ContentTemplate>
<DataTemplate>
<TextBox ContextMenu="{x:Null}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="50"></TextBox>
</DataTemplate>
</ContentControl.ContentTemplate>
</ContentControl>
</Grid>
</Window>

但这就是我得到的:

enter image description here

下面的代码工作正常:

<Grid>
<TextBox ContextMenu="{x:Null}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="50"></TextBox>
</Grid>

为什么会这样?

更新。

根据已接受的答案,我创建了一个派生自 TextBox 的类,以便能够显示父上下文菜单。

    public class TextBoxNoMenu: TextBox
{
public TextBoxNoMenu()
{
ContextMenu = null;
}
}

最佳答案

Why is this happening?

这是一个有趣的例子,控件的行为会根据设置属性的位置/方式而改变。

TextBox 默认提供自己的上下文菜单。 唯一它不会执行此操作的时间是当您将 ContextMenulocal value 明确设置为 null 时。这就是您的简单示例中发生的情况,其中 TextBox 直接位于 Grid 中。

但是,当您在模板中设置属性时,您实际上并没有设置本地值;您正在设置“父模板”值。如果您使用 DependencyPropertyHelper.GetValueSource() 检查该值,您将看到基值源是 ParentTemplate 而不是 Local。因此,菜单仍然会被覆盖。

参见 Dependency Property Value Precedence有关不同类型的依赖属性值源的更多信息。

@OmegaMan 关于分配“隐藏”上下文菜单的建议似乎很有效。

关于c# - WPF 上下文菜单 = {x :Null} but still shows menu inside ContentControl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26385227/

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