在按钮悬停时将文本和路径更改为不同颜色
Posted
技术标签:
【中文标题】在按钮悬停时将文本和路径更改为不同颜色【英文标题】:change text and path to diffrent color on hover of button 【发布时间】:2016-11-16 05:52:30 【问题描述】:我有一个包含路径和文本的按钮。像这样
在按钮悬停时,它应该像这样改变颜色
这是我已经做过的事情 Xaml 文件
<Button Grid.Row="1" Grid.Column="0" Style="StaticResource DashBordMenuButton" >
<StackPanel >
<Path Name="DIcon1" Data="StaticResource IconReporting" Fill="Binding Foreground, RelativeSource=RelativeSource Mode=FindAncestor, AncestorType=Button" HorizontalAlignment="Center" ></Path>
<TextBlock HorizontalAlignment="Center" Margin="0,10,0,0" > DASHBORD</TextBlock>
<TextBlock LineHeight="25" TextWrapping="Wrap" LineStackingStrategy="BlockLineHeight" Margin="0,20,0,0" Text="Minir All Servers,Clients and Activies"></TextBlock>
</StackPanel>
</Button>
风格
<Style x:Key="DashBordMenuButton" TargetType="Button">
<Setter Property="Margin" Value="10"></Setter>
<Setter Property="Background" Value="White"/>
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="1,1,1,4" BorderBrush="Gray" Background="TemplateBinding Background">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF36D8E0"/>
<Setter Property="Foreground" Value="White"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
悬停时它可以正常工作。但默认情况下,路径图标也会变成黑色而不是白色。我该如何解决这个问题 提前致谢
【问题讨论】:
【参考方案1】:您的路径由 XAML 下方的按钮 Forground
颜色填充
Fill="Binding Foreground, RelativeSource=RelativeSource Mode=FindAncestor, AncestorType=Button"
因此,在您的style
触发Hover
之前,您的Button
的Forground
默认为黑色。您可以通过在触发器开始之前添加一个设置器来更改它,即。为您的Button
中的Forground
添加setter
,如下所示。
<Style x:Key="DashBordMenuButton" TargetType="Button">
<Setter Property="Margin" Value="10"></Setter>
<Setter Property="Background" Value="White"/>
<Setter Property="OverridesDefaultStyle" Value="True" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Foreground" Value="#FF36D8E0"></Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border Name="border" BorderThickness="1,1,1,4" BorderBrush="Gray" Background="TemplateBinding Background">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF36D8E0"/>
<Setter Property="Foreground" Value="White"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
将setter
添加到style
<Setter Property="Foreground" Value="#FF36D8E0"></Setter>
【讨论】:
以上是关于在按钮悬停时将文本和路径更改为不同颜色的主要内容,如果未能解决你的问题,请参考以下文章
按钮,文本和内联元素的不同颜色,两者都应该能够在悬停时改变颜色