XAML - 逗号分隔的依赖属性

4
我有一个名为AppPreferences的自定义类。这个类有一个名为Color的依赖属性,它代表着类型为Colors(这是一个自定义枚举器)的枚举值。下面是我的AppPreferences代码:
public class AppPreferences
{
  public static readonly DependencyProperty ColorProperty = DependencyProperty.RegisterAttached(
  "Color",
  typeof(MyServiceProxy.Colors),
  typeof(AppPreferences),
  new PropertyMetadata(MyServiceProxy.Colors.DEFAULT, new   PropertyChangedCallback(OnColorChanged))
  );

  private static void OnColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    // Do Stuff
  }
}

作为开发人员,我会添加这个代码到我的UI元素中以帮助确定颜色。例如,我会像这样做:
```css background-color: #ff0000; /*红色*/ ```
其中的`#ff0000`表示红色。
<TextBox custom:AppPreferences.Color="Black" ... />

我现在需要支持备用颜色。换句话说,我想提供一个逗号分隔的颜色列表,类似于以下内容:

<TextBox custom:AppPreferences.Color="Black,Blue" ... />

我的问题是,如何更新我的依赖属性和OnColorChanged事件处理程序以支持多个值?
谢谢!

1
可能是wpf dependency property enum collection的重复问题。 - Heinzi
2个回答

0

你想要实现的机制被称为“附加属性”。

阅读this获取更多信息。

这里是一个简短的代码摘录,可以完成所有操作:

public static readonly DependencyProperty IsBubbleSourceProperty = 
 DependencyProperty.RegisterAttached(
  "IsBubbleSource",
  typeof(Boolean),
  typeof(AquariumObject),
  new FrameworkPropertyMetadata(false, 
    FrameworkPropertyMetadataOptions.AffectsRender)
);
public static void SetIsBubbleSource(UIElement element, Boolean value)
{
  element.SetValue(IsBubbleSourceProperty, value);
}
public static Boolean GetIsBubbleSource(UIElement element)
{
  return (Boolean)element.GetValue(IsBubbleSourceProperty);
}

阅读 this 了解如何在 Xaml 中使用逗号分隔的枚举。

同时,您可能还想查看this


0

为了允许这种语法,您应该确保您拥有逐个标志的枚举。这可以通过将FlagsAttribute添加到您的枚举中来实现。

[Flags]
enum Colors
{
    Black,
    ...
}

对于标志位枚举,行为基于 Enum.Parse 方法。您可以使用逗号将多个值指定为标志位枚举。但是,您不能组合非标志位枚举的枚举值。例如,您不能使用逗号语法来尝试创建针对非标志枚举的多个条件操作的触发器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接