在XAML中指定命名颜色的透明度级别 [英] Specify transparency level of a named color in XAML

查看:70
本文介绍了在XAML中指定命名颜色的透明度级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XAML中是否有一种方法可以从具有不同自定义透明度级别的命名颜色创建颜色对象?例如,

Is there a way in XAML to create a color object from a named color with different custom transparency level? e.g.

<Label Background="{SkyBlue;220}" />

我知道这行不通,只是想举一个例子。

I know this doesn't work, but just wanted to quote an example.

推荐答案

其中一种情况是您自己找到答案。这是任何将来的读者的正确方法:

One of those times when you find the answer yourself. Here's the correct way for any future reader:

<Label.Background>
    <SolidColorBrush Color="SkyBlue" Opacity=".9" />
</Label.Background>

不透明度的范围在0和1,1之间完全不透明(不透明)。

Opacity ranges between 0 and 1, 1 being full opaque (non-transparent).

关于@Dai的评论,此方法的确没有如果要引用已经设置了某种透明度的颜色资源,请重置或覆盖指定颜色的透明度级别。例如,如果您的资源颜色是 SkyBlue ,透明度设置为0.5,现在您想将其设置为0.7,则上述方法将无法直接使用。

Regarding @Dai's comment, this method indeed doesn't reset or override the transparency level of the specified color in case you're referencing a color resource that already has set some transparency. For example if your resource color is SkyBlue with transparency set to 0.5, and now you want to set it to 0.7 instead, the above method won't work directly.

要处理这种情况,您需要做的是创建一个小的 Converter 来重置输入颜色的alpha分量。 。像这样的东西:

To handle that situation, all you need to do is to create a little Converter that resets the alpha component of the input color. Something like this:

public class NoTransparencyConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    var C = ((Color)value);
    return Color.FromArgb(0xFF, C.R, C.G, C.B);
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    throw new NotSupportedException();
  }
}

,然后在您的XAML中使用它:

and then use it in your XAML:

<SolidColorBrush Color="{Binding Path="YOUR_COLOR_RESOURCE" Converter={x:Static NoTransparencyConverter}}" Opacity=".9" />

这篇关于在XAML中指定命名颜色的透明度级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆