WPF自定义Ellipse模板Button的鼠标悬浮高亮修复及颜色修改方法
修复WPF椭圆按钮的悬浮/点击高亮效果
当你自定义Button的ControlTemplate时,默认的交互视觉状态(比如鼠标悬浮、点击)会被覆盖,所以原来的高亮效果失效了。要恢复效果,需要在模板里加入VisualStateManager来定义这些状态的视觉变化。
修改后的完整代码
<Button x:Name="ButtonEquals" Grid.Column="4" Grid.Row="6" Width="47" Height="47" Content="=" Foreground="White" BorderBrush="{x:Null}" Background="#FFFF9500"> <Button.Template> <ControlTemplate TargetType="Button"> <Grid> <Ellipse x:Name="ButtonEllipse" Fill="#FFFF9500"/> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> <!-- 添加视觉状态管理 --> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <!-- 鼠标悬浮状态 --> <VisualState x:Name="MouseOver"> <Storyboard> <ColorAnimation Storyboard.TargetName="ButtonEllipse" Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)" To="#FFE68A00" Duration="0:0:0.1"/> </Storyboard> </VisualState> <!-- 鼠标点击状态 --> <VisualState x:Name="Pressed"> <Storyboard> <ColorAnimation Storyboard.TargetName="ButtonEllipse" Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)" To="#FFCC7A00" Duration="0:0:0.1"/> </Storyboard> </VisualState> <!-- 默认正常状态 --> <VisualState x:Name="Normal"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </ControlTemplate> </Button.Template> </Button>
关键说明
- 给Ellipse命名为
ButtonEllipse,方便在视觉状态里定位修改它的填充色。 VisualStateGroup里定义了CommonStates(通用状态组),包含Normal(默认)、MouseOver(悬浮)、Pressed(点击)三个状态。- 用
ColorAnimation实现颜色过渡,Duration控制颜色变化的快慢,0.1秒是比较自然的过渡速度。
修改高亮颜色的方法
- 直接修改
MouseOver和Pressed状态里的To属性值,比如把悬浮色改成#FFFFB74D,点击色改成#FFE57C00。 - 如果要统一管理所有按钮的颜色,可以把颜色定义为资源:
然后在模板里绑定这些资源:<Window.Resources> <SolidColorBrush x:Key="ButtonNormalBrush" Color="#FFFF9500"/> <SolidColorBrush x:Key="ButtonHoverBrush" Color="#FFE68A00"/> <SolidColorBrush x:Key="ButtonPressedBrush" Color="#FFCC7A00"/> </Window.Resources><Ellipse x:Name="ButtonEllipse" Fill="{StaticResource ButtonNormalBrush}"/> <!-- 视觉状态里的ColorAnimation改成绑定资源的Color --> <ColorAnimation Storyboard.TargetName="ButtonEllipse" Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)" To="{Binding Source={StaticResource ButtonHoverBrush}, Path=Color}" Duration="0:0:0.1"/>
内容的提问来源于stack exchange,提问作者IllusiVeXI _ 11
相关产品推荐
相关产品推荐

