如果mouseOver已被覆盖,则无法再更改背景按钮属性

问题描述

在下图中,我有3个按钮(UserControl),在这些按钮上,我更改了认的mouSEOver效果。在图片中,我当前将鼠标悬停在按钮1上。

enter image description here

这是我使用的代码

<Style x:Key="ButtonMouSEOver" targettype="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate targettype="{x:Type Button}">
                <Border>
                    <Border.Style>
                        <Style targettype="{x:Type Border}">
                             <Style.Triggers>
                                <Trigger Property="IsMouSEOver" Value="True">
                                    <Setter Property="Background" Value="#404040"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </Border.Style>
                    <Grid Background="Transparent">
                        <ContentPresenter></ContentPresenter>
                    </Grid>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我的用户控制按钮:

<Button HorizontalContentAlignment="Stretch" Style="{StaticResource ButtonMouSEOver}" VerticalContentAlignment="Stretch" Background="{Binding ButtonColor}" BorderThickness="0">

但是现在,我无法使用Background属性更改按钮的颜色。有什么想法吗?

解决方法

当覆盖std::put_time时,必须小心使用ControlTemplate绑定到模板化目标控件的属性,否则它们将使用其默认值或您在模板,但不能直接覆盖它们,也不能在TemplateBinding中覆盖它们。

在您的示例中,您必须将Style的{​​{1}}与Background绑定,以便它使用模板化{{ 1}}。您应该对Border的所有属性执行此操作,以启用不同的样式。

TemplateBinding

来自Background的{​​{3}}:

将控件模板中的属性值链接为模板控件上另一个属性的值。

这是控件模板的简化版本,具有用于背景的模板绑定以及以其样式定义的默认值,可以用其他样式或直接在按钮上覆盖它。

Button