【问题标题】:Programmatically set foreground text color of button以编程方式设置按钮的前景文本颜色
【发布时间】:2019-10-11 03:26:59
【问题描述】:

这是针对 UWP 应用的。 ReturnCharacter() 将返回 o 或 x。如果返回 x,则设置为蓝色。否则(返回 o)并设置红色。然后,使用先前设置的颜色在按钮上写入 x 或 o。所以,我们应该在按钮上得到一个蓝色的 x 或一个红色的 o。尝试了以下但它不起作用。我只是得到一个棕色的x或o。想知道这种颜色是从哪里来的。另外,有没有办法使用十六进制值而不是 RGB 值来表示颜色?

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        char c = ReturnCharacter();

        if (c == 'x')
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(51, 178, 255, 0));
        }
        else
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 104, 51, 0));
        }

        button1.Content = c;
    }

【问题讨论】:

    标签: c# uwp


    【解决方案1】:

    Color.FromArgb() 有 4 个参数。第一个是 Alpha 通道。如果您希望颜色完全不透明,则 255 是正确的值。

    你可能想要:

    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        char c = ReturnCharacter();
    
        if (c == 'x')
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 51, 178, 255));
        }
        else
        {
            button1.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 104, 51));
        }
    
        button1.Content = c;
    }
    

    或更简单有效:

    SolidColorBrush blue = new SolidColorBrush(Color.FromArgb(255, 51, 178, 255));
    SolidColorBrush red = new SolidColorBrush(Color.FromArgb(255, 255, 104, 51))
    
    private void Button1_Click(object sender, RoutedEventArgs e)
    {
        char c = ReturnCharacter();
        button1.Foreground = c == 'x' ? blue : red;
        button1.Content = c;
    }
    

    【讨论】:

    • 使用第一个解决方案时,我总是得到红色/橙色 x 或 o。从来没有蓝色。对于第二种解决方案,它说“无法将类型 'Windows.UI.Xaml.Media.SolidColorBrush' 隐式转换为 'Windows.UI.Color'
    • 第一个解决方案有效。我正在检查错误的字符。第二种解决方案仍然存在隐式转换问题。
    • 修复了第二个。
    • 感谢您的出色回答。
    【解决方案2】:

    Color.FromArgb 需要 ARGB 组件,按此顺序

    难怪你会得到以下颜色:

    你想要这个:

    Color.FromArgb(255, 51, 178, 255);
    Color.FromArgb(255, 255, 104, 51);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-02
      • 2021-05-20
      • 2016-12-28
      • 1970-01-01
      • 2012-09-25
      • 2021-10-18
      • 1970-01-01
      • 2014-06-24
      相关资源
      最近更新 更多