azulBonnet azulBonnet - 18 days ago 5
C# Question

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

Can you see what maybe I'm doing wrong? This is my first time trying to use attached properties and am not sure of the limitations.

Here is my class for declaring the attached property:

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

}


Here is my style. I get a blue squiggle under the Property="..." that says "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>


This is how I'm trying to use it in my UserControl:

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

Answer

When you're defining your dependency property, you declare it to be of type string, yet the default metadata you provide specifies false as the default value (new PropertyMetadata(false)), which is of type bool, hence the error. You should specify a string value as the default value:

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

Or don't specify any default value all, in which case the default will be null:

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