【发布时间】:2014-10-20 09:58:57
【问题描述】:
我有一个自定义控件,它的 DependencyProperty 类型为 Brush(类似于背景颜色的属性)。
用户可以使用标准的 Visual Studio 颜色属性包设置颜色。
我想要的是排除设置空画笔(带有禁止框的画笔)的可能性。
我尝试以这种方式使用CoerceValue 回调:
MyBackgroundColorProperty = DependencyProperty.Register("MyBackgroundColor", typeof(Brush), typeof(MyObject), new FrameworkPropertyMetadata(Brushes.Black, null, CoerceCurrentColor));
CoerceCurrentColor 在哪里:
private static object CoerceCurrentColor(DependencyObject d, object baseValue)
{
if (baseValue == null)//Null brush can't be permitted
return new SolidColorBrush(Colors.Transparent);
return baseValue as Brush;
}
这工作......只有第一次。
如果我选择“无画笔”,则真实颜色设置为透明。但是现在每次我尝试更改颜色时,都会收到“无效的属性值”消息框错误。为什么?而且,有没有其他方法可以实现这个结果?
【问题讨论】:
标签: c# wpf visual-studio designer coercion