5

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

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

在 Xaml 中设置它非常好,但如果我尝试在样式中设置它:

我在运行时收到 ArguemntNullException(说:“值不能为空。参数名称:属性”)。

我无法弄清楚这里有什么问题。任何提示都适用!

4

1 回答 1

11

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

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

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

private static void FocusedExChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var toolBar = d as ToolBar;
    if (toolBar != null && (bool)e.NewValue)
    {
        toolBar.Focus();
    }
}
于 2012-11-10T11:40:37.983 回答