为了在不直接更改模板的情况下轻松地更改特定于模板的按钮刷,我决定制作一个DependencyProperty,它将绑定到特定于模板的画笔上。这样,我就可以像更改任何其他常规属性一样简单地更改这个画笔。然而,在实现这个DependencyProperty之后,我遇到了一个错误:“名称”"ExtensionClass“不存在于名称空间”clr-命名空间:扩展“中。是什么导致了这个错误?
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);
}
}
}发布于 2021-07-17 10:18:04
除了绑定的问题(这个问题在重复问题的答案中提到)之外,您还必须意识到您正在声明一个附加财产,它必须在RegisterAttached方法中注册。
此外,在寄存器和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}}"/>https://stackoverflow.com/questions/68419306
复制相似问题