正如您在 DefaultButtonStyle 中所见,VisualState PointerOver 将按钮的
Background
更改为名为 ButtonBackgroundPointerOver 的 ThemeResource。
(如果您不知道如何找到 generic.xaml,请查看此 answer。)
您可以像这样覆盖ButtonBackgroundPointerOver:
<Button>
<Button.Resources>
<Button.Resources>
<SolidColorBrush
x:Key="ButtonBackgroundPointerOver"
Color="HotPink" />
</Button.Resources>
</Button.Resources>
</Button>
不幸的是,Button 控件没有针对焦点事件的 VisualState。您可以做的是在代码隐藏中使用
Background
和 GotFocus
事件更改按钮的 LostFocus
,但您也可以创建自定义控件:
AwesomeButton.cs
public class AwesomeButton : Button
{
public static readonly DependencyProperty FocusedBackgroundProperty =
DependencyProperty.Register(
nameof(FocusedBackground),
typeof(Brush),
typeof(AwesomeButton),
new PropertyMetadata(default));
public AwesomeButton()
{
GotFocus += AwesomeButton_GotFocus;
LostFocus += AwesomeButton_LostFocus;
}
public Brush FocusedBackground
{
get => (Brush)GetValue(FocusedBackgroundProperty);
set => SetValue(FocusedBackgroundProperty, value);
}
private Brush? BackgroundBeforeGettingFocus { get; set; }
private void AwesomeButton_GotFocus(object sender, RoutedEventArgs e)
{
BackgroundBeforeGettingFocus = Background;
Background = FocusedBackground;
}
private void AwesomeButton_LostFocus(object sender, RoutedEventArgs e)
{
Background = BackgroundBeforeGettingFocus;
}
}
并像这样使用它:
<local:AwesomeButton
x:Name="AwesomeButton"
Width="{x:Bind Width}"
Height="{x:Bind Height}"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Transparent"
BorderThickness="0"
FocusedBackground="LightGreen">
<Button.Resources>
<SolidColorBrush
x:Key="ButtonBackgroundPointerOver"
Color="HotPink" />
</Button.Resources>
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Orientation="Vertical">
<FontIcon
VerticalAlignment="Center"
FontFamily="{StaticResource SymbolThemeFontFamily}"
FontSize="{x:Bind IconSize}"
Glyph="{x:Bind Glyph}" />
<TextBlock
Margin="0,10,0,0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="{x:Bind FontSize}"
Text="{x:Bind Label}" />
</StackPanel>
</local:AwesomeButton>