【问题标题】:Avoid "null" Brush in a DependencyProperty避免在 DependencyProperty 中使用“null”画笔
【发布时间】: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


    【解决方案1】:

    使用 IValueConverter 处理 null 可能性。

    【讨论】:

    • 好主意!我会尽快尝试,我会告诉你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2019-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多