c# - 如何在 UWP 中输入 PointerEnter 时更改 HyperlinkBut​​ton 背景和前景色

标签 c# uwp windows-10-universal uwp-xaml

这是我使用 C# 和 XAML 编写的示例 UWP 代码 我在 MainPage 方法中创建了一个超链接按钮,并设置了前景和背景等样式属性。

现在我想在像鼠标悬停这样的 PointerEntered 事件触发时更改背景和前景色,在这种情况下,只有字体大小发生变化,但颜色没有变化

public MainPage(){
    this.InitializeComponent();

    var hLinkButton = new HyperlinkButton();

    hLinkButton.Name = "LearnMoreHyperLink";
    hLinkButton.Content = "Learn More...";

    hLinkButton.Background = new SolidColorBrush(Colors.Red);
    hLinkButton.Foreground = new SolidColorBrush(Colors.White);
    hLinkButton.FontWeight = FontWeights.SemiBold;
    hLinkButton.FontSize = 18.0;

    hLinkButton.PointerEntered += OnPointerEntered;
    LayoutGrid.Children.Add(hLinkButton);
}

private void OnPointerEntered(object sender, PointerRoutedEventArgs e){
    var hLButton = sender as HyperlinkButton;
    hLButton.Background = new SolidColorBrush(Colors.White);
    hLButton.Foreground = new SolidColorBrush(Colors.Red);
    hLButton.FontSize = 30.0;
}

// Only fontsize effecting on mouseover, background and foreground is not working

最佳答案

您可以覆盖 HyperlinkBut​​ton 的样式模板来实现此目的。

为此,您需要右键单击您的 HyperLinkBut​​ton > 编辑模板 > 编辑副本。 然后在visual state中添加相关代码。在您的例子中,视觉状态是“PointerOver”。

以下代码将使 HyperLinkBut​​ton 的前景变为红色,背景变为白色。

  <VisualState x:Name="PointerOver">
      <Storyboard>
         <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Foreground">
           <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFF0000" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                     Storyboard.TargetProperty="Background">
        <DiscreteObjectKeyFrame KeyTime="0" Value="#FFFFFFFF" />
       </ObjectAnimationUsingKeyFrames>
      </Storyboard>
   </VisualState>

编辑

在 c# 代码中,您所做的是更改 HyperLinkBut​​ton 的背景色和前景色,这会覆盖控件的“正常”视觉状态 的颜色。 . 当指针位于您的控件上方时,XAML 中预定义的默认控件样式(for "PointerOver"state)显示的是它应该显示的颜色,因此您只能在指针已从您的控件中删除..

因此,在我看来,覆盖控件的 xaml 样式是正确的,也是 PointerOver 事件的最佳解决方案。

Pointer over

如果您对此有任何进一步的问题,请提出。如果需要,我很乐意给出适当的解释。

关于c# - 如何在 UWP 中输入 PointerEnter 时更改 HyperlinkBut​​ton 背景和前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47345504/

相关文章:

c# - 通用 CRC (8/16/32/64) 组合实现

c# - 包含许多控件的页面上的 AutoEventWireup false (C#)

c# - 使用 C# Thread 删除文件

unit-testing - UWP MSTest 不起作用

C# 定时器回调在每个循环中使用函数的返回值

c++ - 在 C++ winrt 导航 View 中,如何找到已选择/单击的导航项?

c# - 在 Visual Studio Code 中创建 UWP 解决方案

c# - 捕获 MouseButtons.XButton1/2 用于向前/向后导航 Windows 10

azure - 在 Azure 应用服务 C# 通用应用程序中截断 EasyTable

c# - 如何在 UWP 中创建 Tab Header Pivot 控件?