Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

wpf - Specify transparency level of a named color in 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

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

Edit

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.

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();
  }
}

and then use it in your XAML:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...