Trigger on attached property in a border style. Error: Type initialization failed

Trigger on attached property in a border style. Error: Type initialization failed

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

这是我的 class 声明附件 属性:

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

}

这是我的风格。我在 属性="..." 下方看到一条蓝色波浪线,上面写着 "Type 'ControllerAttachProp' initalization failed: The type initializer for 'ControllerAttachedProp' threw an exception"

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

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

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