【发布时间】:2020-11-23 14:50:23
【问题描述】:
我正在尝试使用自定义 DependencyProperty 对我的应用程序 Button 进行风格化
依赖声明:
public static class Button
{
public static readonly DependencyProperty BackgroundHoverProperty;
static Button()
{
BackgroundHoverProperty = DependencyProperty.RegisterAttached(
"BackgroundHover",
typeof(Brush),
typeof(Button),
new PropertyMetadata(Application.Current.FindResource("Mask.Hover")));
}
public static Brush GetBackgroundHover(DependencyObject obj)
{
return (Brush)obj.GetValue(BackgroundHoverProperty);
}
public static void SetBackgroundHover(DependencyObject obj, Brush value)
{
obj.SetValue(BackgroundHoverProperty, value);
}
}
按钮样式:
<Style TargetType="Button">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{StaticResource Border.Default}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="TextElement.Foreground" Value="{StaticResource Foreground.Default}" />
<Setter Property="Padding" Value="1" />
<Setter Property="HorizontalContentAlignment" Value="Center" />
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="controls:Button.BackgroundHover" Value="Blue" />
<Setter Property="Template" Value="{StaticResource ButtonTemplate}" />
</Style>
按钮模板:
<ControlTemplate x:Key="ButtonTemplate" TargetType="Button">
<Grid>
<Border
x:Name="Border"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
SnapsToDevicePixels="True" />
<ContentPresenter
x:Name="Content"
RecognizesAccessKey="True"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentStringFormat="{TemplateBinding ContentStringFormat}"
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Focusable="False" />
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter
Property="Background"
TargetName="Border"
Value="{Binding (controls:Button.BackgroundHover), // <--- Here is the binding
RelativeSource={RelativeSource Self}}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
我不知道我做错了什么。
编辑:我也试过RelativeSource={RelativeSource TemplatedParent},但仍然没有结果。
【问题讨论】:
-
到底出了什么问题?你有错误吗?输出窗口中是否有任何绑定错误?它只是没有显示鼠标悬停状态吗?
-
不,我没有收到任何错误,只是当我将鼠标悬停在按钮上时,它不会变为蓝色。我还注意到,当我使用该特定绑定时,单击变得非常不可靠,而如果我用硬编码颜色替换它,它会完美运行。
-
@reonZ:您还应该从示例中删除
StaticResource Border.Default和任何其他静态资源,因为您没有在示例代码中包含这些资源。
标签: wpf binding dependency-properties