Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attached Property + Style -> ArgumentNullException

I have created a very Simple attached Property:

public static class ToolBarEx 
{
    public static readonly DependencyProperty FocusedExProperty =
        DependencyProperty.RegisterAttached(
            "FocusedEx", typeof(bool?), typeof(FrameworkElement),
            new FrameworkPropertyMetadata(false, FocusedExChanged));

    private static void FocusedExChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is ToolBar)
        {
            if (e.NewValue is bool)
            {
                if ((bool)e.NewValue)
                {
                    (d as ToolBar).Focus();
                }
            }
        }
    }

    public static bool? GetFocusedEx(DependencyObject obj)
    {
        return (bool)obj.GetValue(FocusedExProperty);
    }

    public static void SetFocusedEx(DependencyObject obj, bool? value)
    {
        obj.SetValue(FocusedExProperty, value);
    }
}

Setting this in Xaml works perfectly fine, but if I try setting it within a Style:

I receive an ArguemntNullException during the Runtime (saying: "Value cannot be null. Parameter name: property").

I cannot figure what is wrong here. Any hint is appriciated!

like image 961
Jaster Avatar asked Nov 10 '12 11:11

Jaster


1 Answers

A common mistake made when registering attached dependency properties is to incorrectly specify the ownerType argument. This must always be the registering class, ToolBarEx here:

public static readonly DependencyProperty FocusedExProperty =
    DependencyProperty.RegisterAttached(
        "FocusedEx", typeof(bool?), typeof(ToolBarEx),
        new FrameworkPropertyMetadata(false, FocusedExChanged));

And just for avoiding unnecessary code in the property changed handler you could safely cast NewValue to bool:

private static void FocusedExChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var toolBar = d as ToolBar;
    if (toolBar != null && (bool)e.NewValue)
    {
        toolBar.Focus();
    }
}
like image 108
Clemens Avatar answered Oct 05 '22 00:10

Clemens