我正在尝试更改鼠标悬停在按钮上时的默认边框颜色,但我无法让它工作。我认为这样可以正常工作,但显然不会:
<Button>
<Button.Resources>
<Color x:Key="ControlMouseOverColor">somecolor</Color>
</Button.Resources>
</Button>
有没有办法做到这一点?
答案 0 :(得分:2)
这是您需要做一些稍微复杂的事情来完成WPF中的简单操作的情况之一:)。实际上,您需要覆盖Button控件的ControlTemplate,因为鼠标悬停在按钮上时的边框颜色由默认的ControlTemplate决定。下面是一个带有默认CotrolTemplate的按钮,减去IsMouseOver setter设置为红色:
<Button>
<Button.Template>
<ControlTemplate TargetType="{x:Type ButtonBase}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ContentPresenter x:Name="contentPresenter" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="Button.IsDefaulted" Value="True">
<Setter Property="BorderBrush" TargetName="border" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" TargetName="border" Value="#FFBEE6FD"/>
<Setter Property="BorderBrush" TargetName="border" Value="Red"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" TargetName="border" Value="#FFC4E5F6"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FF2C628B"/>
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Setter Property="Background" TargetName="border" Value="#FFBCDDEE"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FF245A83"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Background" TargetName="border" Value="#FFF4F4F4"/>
<Setter Property="BorderBrush" TargetName="border" Value="#FFADB2B5"/>
<Setter Property="TextElement.Foreground" TargetName="contentPresenter" Value="#FF838383"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Button.Template>
Click
</Button>
答案 1 :(得分:0)
WPF中对此的正常解决方案是属性触发器:
<Button>
<Button.Style>
<Style TargetType="{x:Type Button}">
<Setter Property="BorderBrush" Value="Black"></Setter>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="Red"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
属性触发器旨在在条件变为true时作出反应,但在该条件变为false时恢复其先前的状态。所以我们在这里说:当IsMouseOver属性变为true时,将按钮的边框画笔设置为红色。当条件变为false时,它将变回黑色(我不确定边框画笔的默认颜色是什么,所以你可以删除第4行)