我正在尝试创建一个 UWP 按钮,当鼠标指针悬停在其上时,该按钮将更改背景颜色。我遇到的麻烦是,默认情况下,它似乎已经做到了这一点,但不是我想要的颜色。当我将鼠标悬停在红色按钮上时,它会变成默认的灰色,然后当我将鼠标移开时又会变回灰色。我用 C# 编写了代码,尝试将鼠标悬停在其上时使其变成蓝色
private void button_PointerEntered_1(object sender, PointerRoutedEventArgs e)
{
button.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 0, 0, 255));
}
private void button_PointerExited_1(object sender, PointerRoutedEventArgs e)
{
button.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 0, 0));
}
下面是按钮的 XAML 代码
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Button x:Name="button"
Content="Button"
HorizontalAlignment="Left"
Margin="417,188,0,0"
VerticalAlignment="Top"
Height="230"
Width="461"
FontSize="72"
ManipulationMode="None"
PointerEntered="button_PointerEntered_1"
PointerExited="button_PointerExited_1">
<Button.Foreground>
<SolidColorBrush Color="Black"/>
</Button.Foreground>
<Button.Background>
<SolidColorBrush Color="Red"/>
</Button.Background>
</Button>
</Grid>
2018 年更新答案
实现它的最简单方法是覆盖按钮字典中的资源(对于您想要的主题)
您可以更改名为的资源键的值Button<Property>PointerOver
为了达到效果:
<Button Background="Red" Foreground="Black"> <!-- These are only applied when your button is not being hovered-->
<Button.Resources>
<ResourceDictionary>
<ResourceDictionary.ThemeDictionaries>
<ResourceDictionary x:Key="Dark">
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Red"/>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="Black"/>
</ResourceDictionary>
<ResourceDictionary x:Key="Light">
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Red"/>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="Black"/>
</ResourceDictionary>
</ResourceDictionary.ThemeDictionaries>
</ResourceDictionary>
</Button.Resources>
</Button>
这是如何完成此操作的示例 https://learn.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/xaml-styles#lightweight-styling在微软官方文档中得到以下结果:
And 这是您可以覆盖的资源列表 https://learn.microsoft.com/en-us/uwp/api/Windows.UI.Xaml.Controls.Button#control-style-and-template在一个按钮中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)