2012-07-26 85 views
0

我已经定义了一个依赖属性,它使用枚举来更新按钮的背景颜色。当它运行时,我得到一个“默认值类型不匹配属性类型'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> 

回答

1

1) 因为你不能施放false(bool)WarningLevels

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

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

Value="wlError" 

是一个字符串,它不能转换为enum,也没有类型转换器。解决这个问题的最简单方法就是延长你的价值:

<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> 
+0

我问你的第二点。有[类型转换器](http://msdn.microsoft.com/en-us/library/cc645047.aspx)支持[通用枚举](http://msdn.microsoft.com/en-us/library /system.componentmodel.enumconverter.aspx)。 – 2012-07-27 01:48:33