c# - XAML - 逗号分隔的依赖属性

标签 c# xaml dependency-properties

我有一个名为 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 元素中以帮助确定颜色。例如,我会做这样的事情:

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

我现在需要支持后备颜色。换句话说,我希望能够提供类似于以下内容的以逗号分隔的颜色值列表:

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

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

谢谢!

最佳答案

您尝试实现的机制称为“附加属性”。

阅读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 .

关于c# - XAML - 逗号分隔的依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8896762/

相关文章:

c# - 将 Directory.GetFiles 与类似正则表达式的过滤器一起使用

silverlight - 属性(property)值(value)继承

wpf - XAML 中的简单动画书动画

c# - 如何在 MVVM 模式 wpf 中绑定(bind) StrokeDashArray 属性

c# - 如何从方法中发送和检索

c# - 如何使用Extend Custom Control和在Window中使用

c# - 从 ListBoxItem 获取 ListBox 对象

c# - 使用泛型委托(delegate)时如何理解逆变?

c# - 查找选定的 WPF 列表框条目

c# - 在单独的 AppDomain 中传递和执行委托(delegate)