将 DependencyProperty 实施到 TemplateBinding 时发生 XDG0008 错误

XDG0008 error occuring while implementing DependencyProperty into TemplateBinding

为了在不直接更改模板的情况下轻松更改按钮的特定于模板的画笔,我决定创建一个 DependencyProperty 来绑定到特定于模板的画笔。这样,我就可以像更改任何其他常规 属性 一样轻松地更改此笔刷。但是,在实现这个 DependencyProperty 之后,我遇到了一个错误:“名称“ExtensionClass”在命名空间“clr-namespace:extensions”中不存在。”是什么原因导致此错误?

XAML:

<ResourceDictionary xmlns:ext="clr-namespace:Extensions"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero2"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <ControlTemplate x:Key="ButtonBaseControlTemplate1" TargetType="{x:Type ButtonBase}">
        <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Background" TargetName="border" Value="{TemplateBinding Property=ext:ExtensionsClass.MouseOverBackground}"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
</ResourceDictionary>

C#:

namespace Extensions {
    public class ExtensionsClass {
        public static readonly DependencyProperty MouseOverBackgroundProperty = DependencyProperty.Register("MouseOverBackground", typeof(Brush), typeof(Button));

        public static void SetMouseOverBackground(UIElement element, Brush value) {
            element.SetValue(MouseOverBackgroundProperty, value);
        }

        public static Brush GetMouseOverBackground(UIElement element) {
            return (Brush)element.GetValue(MouseOverBackgroundProperty);
        }
    }
}

除了重复问题的答案中涵盖的绑定问题之外,您还必须注意您正在声明一个 attached property,它必须在 RegisterAttached方法。

除此之外,在 Register 和 RegisterAttached 方法中,第三个参数必须是声明 属性 的类型,而不是您打算设置 属性 的元素类型,即这里 typeof(ExtensionsClass)

public static class ExtensionsClass
{
    public static readonly DependencyProperty MouseOverBackgroundProperty =
        DependencyProperty.RegisterAttached(
             "MouseOverBackground",
             typeof(Brush), 
             typeof(ExtensionsClass),
             null);

    public static void SetMouseOverBackground(UIElement element, Brush value)
    {
        element.SetValue(MouseOverBackgroundProperty, value);
    }

    public static Brush GetMouseOverBackground(UIElement element)
    {
        return (Brush)element.GetValue(MouseOverBackgroundProperty);
    }
}

您通过带括号的绑定路径绑定到附加的 属性:

<Setter
    Property="Background"
    TargetName="border"
    Value="{Binding Path=(ext:ExtensionsClass.MouseOverBackground),
            RelativeSource={RelativeSource TemplatedParent}}"/>