C# WPF - 如何修改 ToolBar.ButtonStyleKey 样式
Posted
技术标签:
【中文标题】C# WPF - 如何修改 ToolBar.ButtonStyleKey 样式【英文标题】:C# WPF - How to modify the ToolBar.ButtonStyleKey style 【发布时间】:2022-01-04 00:56:43 【问题描述】:我需要在鼠标悬停时显示工具栏按钮边框,否则将其隐藏。我尝试执行以下操作:
<Style x:Key="x:Static ToolBar.ButtonStyleKey" TargetType="Button" BasedOn="StaticResource x:Static ToolBar.ButtonStyleKey">
<Setter Property="Foreground" Value="Blue"/>
<Setter Property="Control.Background" Value="Transparent" />
<Setter Property="Control.BorderBrush" Value="Transparent" />
<Setter Property="Control.BorderThickness" Value="1" />
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Control.BorderBrush" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
但它没有按预期工作。我期望发生的是鼠标在边框上会变成红色,否则会是透明的。实际结果是它的行为与默认颜色的默认行为类似。 我肯定做错了什么。 有谁知道是什么?
【问题讨论】:
【参考方案1】:当在 ToolBar 中使用时,尝试以下方法覆盖由 ToolBar.ButtonStyleKey 标识的按钮样式。
<ToolBar.Resources>
<Style x:Key="x:Static ToolBar.ButtonStyleKey" TargetType="x:Type Button">
<Setter Property="Foreground"
Value="DynamicResource x:Static SystemColors.ControlTextBrushKey"/>
<Setter Property="Padding" Value="2"/>
<Setter Property="BorderThickness" Value="4"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="x:Type Button">
<Border x:Name="Bd"
SnapsToDevicePixels="true"
Background="TemplateBinding Background"
BorderBrush="TemplateBinding BorderBrush"
BorderThickness="TemplateBinding BorderThickness"
Padding="TemplateBinding Padding">
<ContentPresenter
HorizontalAlignment="TemplateBinding HorizontalContentAlignment"
VerticalAlignment="TemplateBinding VerticalContentAlignment"
SnapsToDevicePixels="TemplateBinding SnapsToDevicePixels"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="Bd" Value="Orange"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ToolBar.Resources>
【讨论】:
以上是关于C# WPF - 如何修改 ToolBar.ButtonStyleKey 样式的主要内容,如果未能解决你的问题,请参考以下文章