附属物+风格 - > ArgumentNullException

时间:2012-11-10 11:26:41

标签: 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);
    }
}

在Xaml中设置此功能非常合适,但如果我尝试在Style中设置它:

                                                                                       

我在运行时收到一个ArguemntNullException(说:“Value不能为null。 参数名称:property“)。

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

1 个答案:

答案 0 :(得分:8)

注册附加依赖项属性时常见的错误是错误地指定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();
    }
}