将按钮模板前景绑定到派生自按钮的 class 的 属性

Bind Button Template Foreground to property of class which derives from Button

我想为我的按钮设置单独的突出显示颜色,所以我创建了一个新的 class "HighlightButton",它派生自 Button 并仅公开一个额外的 属性(DP 属性) - SolidColorBrush HighlightColor.

public class HighlightButton : Button {
    public SolidColorBrush HighlightColor {
        get { return (SolidColorBrush)GetValue(HighlightColorProperty); }
        set { SetValue(HighlightColorProperty, value); }
    }

    // Using a DependencyProperty as the backing store for HighlightColor.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty HighlightColorProperty =
        DependencyProperty.Register("HighlightColor", typeof(SolidColorBrush), typeof(HighlightButton), new PropertyMetadata(new SolidColorBrush(System.Windows.Media.Color.FromRgb(255,255,255))));
}

-

现在我在 XAML:

中使用这个 HighlightButton 而不是 Button
<con:HighlightButton Style="{StaticResource TransparentButton}"
            x:Name="_backButton"
            CommandParameter="{Binding PreviousPageViewModel}" 
            Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType=Window}}"
            HighlightColor="Yellow"/>

-

透明按钮样式在资源字典中定义:

<Style TargetType="con:HighlightButton" x:Name="_transparentButton" x:Key="TransparentButton">
    <Setter Property="Height" Value="50"/>
    <Setter Property="Width" Value="50"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Background="Transparent">
                    <ContentPresenter HorizontalAlignment="Center" 
                                      VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Foreground" Value="{Binding HighlightColor}"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Foreground" Value="Gray"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

如您所见,我希望我的按钮在悬停在按钮上时切换到单独设置的前景色。不幸的是(如您所料)此解决方案不起作用。 WPF 正在我的 ViewModel 内部寻找 属性 HightlightColor(TargetType="Button" 对 HighlightColor 一无所知)。遗憾的是,当我将 TargetType 更改为我的 HighlightButton 时,整个 Style 崩溃了。

是否有可能实现我正在寻找的东西?我做错了什么?

我为模板设置了具体的目标类型

<ControlTemplate TargetType="con:HighlightButton">

并像这样修改绑定

<Setter Property="Foreground" Value="{Binding HighlightColor, RelativeSource={RelativeSource Self}}"/>

顺便说一句,Foreground 和 HighlightColor 默认都是白色。有或没有触发器没有任何明显的区别(例如,如果 <Setter Property="Foreground" Value="White"/> 设置为其他颜色,就会有区别)

另外我更愿意使用 Brush 类型的 属性 来允许不同类型的画笔