gpt4 book ai didi

c# - OverrideMetadata 和默认样式的区别

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:08 25 4
gpt4 key购买 nike

在制作用作拖放目标的自定义控件时,我需要将 AllowDrop 属性设置为 true。我最初使用了以下代码,但发现从未触发过 Drop 事件:

EditorVisual.cs

public class EditorVisual : Control
{
static EditorVisual()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(EditorVisual),
new FrameworkPropertyMetadata(typeof(EditorVisual)));
AllowDropProperty.OverrideMetadata(typeof(EditorVisual),
new FrameworkPropertyMetadata(true));
}
// ...
protected override void OnDrop(DragEventArgs e)
{
base.OnDrop(e);
// this is never called
}
}

主题/Generic.xaml

<Style TargetType="{x:Type local:EditorVisual}">
<Setter Property="Background" Value="LightGreen" />
<!-- Uncomment to make things work -->
<!-- <Setter Property="AllowDrop" Value="True" /> -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:EditorVisual}">
<Border Background="{TemplateBinding Background}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

最终,我将范围缩小到设置 AllowDrop 属性的方式。在 xaml 或默认样式中设置它可以使一切正常工作......这让我感到困惑。为什么使用元数据覆盖不足以接收自定义控件中的拖放事件?

编辑:在任何 CPU 上使用 Visual Studio 2012 和 .Net 4.0 在 Windows 8 上测试 - 调试。

最佳答案

静态构造函数不起作用的原因是 AllowDrop 是一个继承 依赖属性。当您更改 EditorVisual 控件的默认值时,它不会将值传播到可视化树中,这意味着您提供的模板中的控件仍将 AllowDrop 设置为错误。拖放期间的 HitTest 遇到这些控件并失败。

使用样式设置此值(或在控件的实例构造函数中)是完全没问题的。

关于c# - OverrideMetadata 和默认样式的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19073989/

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