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

时间:2016-11-17 18:22:32

标签: c# wpf xaml attached-properties

你能看出我做错了什么吗?这是我第一次尝试使用附加属性,但我不确定这些限制。

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

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);
    }

}

这是我的风格。我在Property =“...”下得到一个蓝色的波形,说“Type'ControllerAttachProp'初始化失败:'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>

这就是我在UserControl中尝试使用它的方法:

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

1 个答案:

答案 0 :(得分:2)

当您定义依赖项属性时,将其声明为string类型,但您提供的默认元数据指定false作为默认值(new PropertyMetadata(false)),是bool类型,因此错误。您应该将字符串值指定为默认值:

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

或者不指定任何默认值all,在这种情况下,默认值为null

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