【问题标题】:Change color of subelements by mouseover通过鼠标悬停更改子元素的颜色
【发布时间】:2015-06-27 07:34:12
【问题描述】:

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

这是代码 (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 也有点困惑(不明白 - 只是复制..)。 Button.Template 是如何工作的?它的用途是什么?

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

【问题讨论】:

  • 看看Visual States,它将在您的按钮模板的顶级元素中定义。
  • @Clemens 几秒钟前发现了这个链接。我会看看这个。

标签: c# wpf button


【解决方案1】:

我们有 MouseEnterMouseLeave 事件。

当鼠标处于控制状态时,使用MouseEnter 更改颜色。

当鼠标离开控件时,使用MouseLeave 更改颜色。

【讨论】:

  • 是的,这是一个选项,但我想知道如何在 XAML 中存档。
  • 我并不是说不使用 xaml。但在这一点上,我猜代码隐藏更容易。但是,那是您的选择。 @JensHorstmann
  • 我同意。但因为这不能回答 XAML 中的问题,所以我不能接受它作为最佳答案。
【解决方案2】:

从未使用过,但将触发器放在按钮的 ControlTemplate 中: 像这样:

<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>

以及 Button.Template 是如何工作的,它的用途是什么? 访问下面的链接 http://www.codeproject.com/Articles/84630/WPF-Customize-your-Application-with-Styles-and-Con

https://msdn.microsoft.com/en-us/library/cc295273.aspx 希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-29
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多