【问题标题】:Dependency property taking an enum采用枚举的依赖属性
【发布时间】:2012-07-26 15:58:26
【问题描述】:

我定义了一个依赖属性,它使用枚举来更新按钮的背景颜色。当它运行时,我得到一个“默认值类型与属性类型‘CurrentWarningLevel’不匹配”异常。依赖属性如下:

public enum WarningLevels
{
    wlError=0,
    wlWarning,
    wlInfo
};

public class WarningLevelButton : Button
{
    static WarningLevelButton()
    {
    }

    public WarningLevels CurrentWarningLevel
    {
        get { return (WarningLevels)GetValue(WarningLevelProperty); }
        set { base.SetValue(WarningLevelProperty, value); }
    }

    public static readonly DependencyProperty WarningLevelProperty =
      DependencyProperty.Register("CurrentWarningLevel", typeof(WarningLevels), typeof(WarningLevelButton), new PropertyMetadata(false));
}

我正在尝试按如下方式使用该属性:

<Trigger Property="local:WarningLevelButton.CurrentWarningLevel" Value="wlError">
    <Setter TargetName="ButtonBody" Property="Background" Value="{StaticResource CtlRedBrush}" />
    <Setter TargetName="ButtonBody" Property="BorderBrush" Value="{StaticResource CtlRedBrush}" />
</Trigger>
<Trigger Property="local:WarningLevelButton.CurrentWarningLevel" Value="wlWarning">
    <Setter TargetName="ButtonBody" Property="Background" Value="{StaticResource GreyGradientBrush}" />
    <Setter TargetName="ButtonBody" Property="BorderBrush" Value="{StaticResource BorderBrush}" />
</Trigger>

【问题讨论】:

    标签: wpf enums dependency-properties


    【解决方案1】:

    1) 因为您不能将false(bool) 转换为WarningLevels

    记住PropertyMetadata的第一个参数是你的默认值。

    2) 你可能会遇到另一个问题。你的触发值

    Value="wlError"
    

    是一个字符串,如果没有类型转换器,它也不能转换为枚举。解决这个问题的最简单方法是扩展您的价值:

    <Trigger Property="local:WarningLevelButton.CurrentWarningLevel" >
        <Trigger.Value>
            <my:WarningLevels>wlError</my:WarningLevels>
        </Trigger.Value>
        <Setter TargetName="ButtonBody" Property="Background" Value="{StaticResource CtlRedBrush}" />
        <Setter TargetName="ButtonBody" Property="BorderBrush" Value="{StaticResource CtlRedBrush}" />
    </Trigger>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 2020-10-28
    • 2014-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多