在边框样式中附加属性上触发。错误:类型初始化失败

在边框样式中附加属性上触发。错误:类型初始化失败

问题描述:

你能看到我可能做错了什么吗?这是我第一次尝试使用附加属性,但我不确定这些限制。在边框样式中附加属性上触发。错误:类型初始化失败

这里是我的声明附加属性类:

public class ControllerAttachedProp : DependencyObject 
{ 

    public static readonly DependencyProperty ControllerStatusProperty = DependencyProperty.RegisterAttached(
     "ControllerStatus", typeof(string), typeof(ControllerAttachedProp), new PropertyMetadata(false)); 

    public static void SetControllerStatus(DependencyObject target, string value) 
    { 
     target.SetValue(ControllerStatusProperty, value); 
    } 

    public static string GetControllerStatus(DependencyObject target) 
    { 
     return (string)target.GetValue(ControllerStatusProperty); 
    } 

} 

这是我的风格。我得到的属性=“...”,说下一个蓝色的波浪线‘型‘ControllerAttachProp’initalization失败的:对于‘ControllerAttachedProp’的类型初始值引发了异常’

<Style x:Key="ForegroundUpdater" TargetType="{x:Type Border}" BasedOn="{StaticResource GreenSquare}"> 
    <Style.Triggers> 
     <Trigger Property="rm:ControllerAttachedProp.ControllerStatus" Value="Paused"> 
      <Setter Property="Background" Value="{StaticResource BlueIsPaused}" /> 
     </Trigger> 
     <Trigger Property="rm:ControllerAttachedProp.ControllerStatus" Value="Disconnected"> 
      <Setter Property="Background" Value="{StaticResource RedIsBad}" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

这就是如何我试图用它在我的用户:

<Border rm:ControllerAttachedProp.ControllerStatus="{Binding    
    SomePropertyInViewModel}" Style="{DynamicResource ForegroundUpdater}"> 
    ... 
    </Border> 

当你定义你的依赖属性,你声明它是string型的,但默认的元数据,你提供指定false为默认值(new PropertyMetadata(false)),这是键入bool,因此错误。你应该指定一个字符串值作为默认值:

public static readonly DependencyProperty ControllerStatusProperty = 
    DependencyProperty.RegisterAttached(
     "ControllerStatus", 
     typeof(string), 
     typeof(ControllerAttachedProp), 
     new PropertyMetadata(string.Empty)); 

,或者不指定任何默认值的所有,在这种情况下,默认会null

public static readonly DependencyProperty ControllerStatusProperty = 
    DependencyProperty.RegisterAttached(
     "ControllerStatus", 
     typeof(string), 
     typeof(ControllerAttachedProp)); 
+0

你是最棒的!谢谢!谢谢! – azulBonnet