C# 通过鼠标悬停更改子元素的颜色

C# 通过鼠标悬停更改子元素的颜色,c#,wpf,button,C#,Wpf,Button,我有以下带有四个按钮和一个图像的窗口栏(有点像功能区): 这是代码(XAML),而隐藏的代码(在C#中)并不有趣: <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Focusable="False" Click="SaveClicked" Margin="10, 0"> <StackPanel Orientation="Horizontal" > <

我有以下带有四个按钮和一个图像的窗口栏(有点像功能区):

这是代码(XAML),而隐藏的代码(在C#中)并不有趣:

<Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" Focusable="False"
    Click="SaveClicked" Margin="10, 0">
    <StackPanel Orientation="Horizontal" >
        <Image x:Name="ImageSave" Height="20" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="20"
           Source="images/titlebar/SaveIconWhite.png" Margin="0,0,0,5" />
        <Label x:Name="LbSave" Content="Save" VerticalAlignment="Stretch" FontSize="14"
           HorizontalAlignment="Left" Foreground="White" />
    </StackPanel>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <ContentPresenter Content="{TemplateBinding Content}"/>
        </ControlTemplate>
    </Button.Template>
</Button>

其他按钮的代码几乎相同

这些按钮感觉有点不舒服,因为它们没有鼠标悬停的效果。 我想在鼠标悬停在按钮上时实现标签的颜色更改。为文件加载和保存而更改图像也很好,但我认为,当我知道如何实现鼠标悬停在标签颜色更改上时,我自己也能做到这一点

在正常情况下,我会尝试使用以下代码将鼠标置于颜色更改上:

<Button.Style>
     <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
       <Style.Triggers>
          <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="DarkGoldenrod"/>
          </Trigger>
       </Style.Triggers>
     </Style>
 </Button.Style>

但这不起作用,因为我已经有了Button.Template,而且我对Button.Template也有点困惑(还没有理解它-只是复制了…)。按钮模板是如何工作的?它的用途是什么

有人能给我一个正确方向的提示吗

我们有很多活动

当鼠标位于控件内时,使用
MouseEnter
更改颜色


使用
MouseLeave
在鼠标脱离控制时更改回颜色。

从未使用过,但将触发器放在按钮的控制模板内: 大概是这样的:

<Button.Template>
        <ControlTemplate TargetType="Button">
            <ContentPresenter Content="{TemplateBinding Content}"/>
        <ControlTemplate.Triggers>
           <Trigger Property="Button.IsMouseOver" Value="True">
             <Setter TargetName="buttonLabel" Property="Foreground" Value="Red"/>
           </Trigger>
         </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>

按钮模板是如何工作的?它的用途是什么? 请访问下面的链接


希望它能帮助您。

是的,当然这是一个选项,但我想知道如何在XAML中归档。我不是说不要使用XAML。但在这一点上,我想代码隐藏更容易。然而,这是你的选择@JensHorstmanni同意。但因为这不能回答XAML中的问题,我不能接受它作为最佳答案。请看一看,它将在按钮模板的顶级元素中定义。@Clemens几秒钟前找到了此链接。我来看看这个。