【问题标题】:How to limit a custom property to available values in XAML如何将自定义属性限制为 XAML 中的可用值
【发布时间】:2018-08-30 18:42:40
【问题描述】:

我有一个枚举声明如下:

public enum DirectionTypes
{
    IN = 2,
    OUT = 1
}

此枚举用于用户控件,我需要在 XAML 中指定控件需要工作的方向。我在每个用户控件上创建了一个依赖属性,如下所示:

public static readonly DependencyProperty DirectionTypeProperty =
        DependencyProperty.Register(
           "DirectionType",
           typeof(DirectionTypes),
           typeof(TransactionGrid), new PropertyMetadata(DirectionTypes.IN));

public DirectionTypes DirectionType
{
    get
    {
        return (DirectionTypes)GetValue(DirectionTypeProperty);
    }
    set
    {
        SetValue(DirectionTypeProperty, value);
    }
}

然后我可以按如下方式使用用户控件:

<local:TransactionGrid x:Name="theGrid" DirectionType="OUT" />

我可以很好地运行程序。问题是 DirectionType="OUT" 在 Visual Studio 2015 中导致智能感知错误。我在 XAML 属性下得到蓝色波浪线,我的设计器不会显示预览,而是说“无效标记”。错误提示 DirectionTypes 的类型转换器不支持从字符串转换。

我缺少什么可以正确解析 XAML。

【问题讨论】:

  • 这只是损坏的 XAML 设计器。尝试重建您的解决方案,或关闭并重新打开 Visual Studio。
  • 这是一个持续数周的问题(多次重新构建、干净的解决方案等......)。我现在只关心它,因为我正在对控件进行更改,而设计器没有给我控件的预览,这让我很烦。

标签: wpf xaml visual-studio-2015 enums


【解决方案1】:

如下明确指定枚举值(假设DirectionTypes与local在同一个命名空间中):

<local:TransactionGrid x:Name="theGrid" DirectionType="{x:Static local:DirectionTypes.OUT}" />

【讨论】:

  • 这行得通,但我希望有一个类似于你如何处理背景颜色的解决方案......我会简单地使用“IN”或“OUT”,而智能感知只会给你这两个字符串作为可用选项。如果没有可以解释如何做到这一点的答案,我会在几天内继续并将其标记为解决方案。
猜你喜欢
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-26
  • 2022-12-02
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
相关资源
最近更新 更多