【问题标题】:why Enum in DependencyProperty returns first value from Enum?为什么 DependencyProperty 中的 Enum 从 Enum 返回第一个值?
【发布时间】:2023-03-18 17:25:01
【问题描述】:

我曾尝试在 DependencyProperty 中使用 Enum,但它总是采用 Enum 的第一个值。

例如 我的枚举:

public enum LayoutType
{
     Horizontal,
     Vertical
}

财产声明:

public static readonly DependencyProperty LayoutTypeProperty =
      DependencyProperty.RegisterAttached("LayoutType", typeof(LayoutType), typeof(ctrlAllLayouts), new PropertyMetadata(null));

我可以在我的 xaml 中访问该属性,但问题是如果将其设置为“水平”或“垂直”,它总是给出值“水平”。

【问题讨论】:

  • +1 用于提供代码和良好的描述

标签: silverlight enums dependency-properties


【解决方案1】:

使用Attached Properties(这些不是您使用RegisterAttached 的普通依赖属性),您还必须声明匹配的 static setter 和 getter 方法才能对其进行解析。 Xaml 解析器实际上使用了这些方法。

例如

public static void SetLayoutType(DependencyObject element, LayoutType value)
{
    element.SetValue(LayoutTypeProperty, value);
}
public static LayoutType GetLayoutType(DependencyObject element)
{
    return (LayoutType)element.GetValue(LayoutTypeProperty);
}

如果缺少这些方法,并且由于您没有在 PropertyMetadata 中指定默认值,它将始终设置为 0,这是您的第一个枚举的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多