我有一个名为 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/