附属物+风格 - > ArgumentNullException

Jas*_*ter 3 c# wpf triggers styles

我创建了一个非常简单的附加属性:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在Xaml中设置它可以很好地工作,但是如果我尝试在Style中设置它:

我在运行时收到一个ArguemntNullException(说:"值不能为null.参数名称:property").

我无法弄清楚这里有什么问题.任何提示都是适当的!

Cle*_*ens 8

注册附加依赖项属性时常犯的错误是错误地指定ownerType参数.这必须始终是注册类,ToolBarEx在这里:

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

只是为了避免在属性更改处理程序中不必要的代码,您可以安全地转换NewValuebool:

private static void FocusedExChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var toolBar = d as ToolBar;
    if (toolBar != null && (bool)e.NewValue)
    {
        toolBar.Focus();
    }
}
Run Code Online (Sandbox Code Playgroud)