Specify transparency level of a named color in XAML
Just to add a little to this one. Yes, you can absolutely set the Opacity
via declarative as you showed in your answer but you don't even need the Dependency Property set, you can do it straight in the hex for the color by utilizing the Alpha
on top of your RGB
values (which by the way offers better performance than opacity
). Where as, say you have the value for Black and you want to give it some opacity. The first 2 octets of that value can be added to accomplish the same thing.
As example;
"#000000" = Black (SOLID)
where as;
"#33000000" = Black (With 20% Opacity)
"#77000000" = Black (With 47% Opacity)
"#E5000000" = Black (With 90% Opacity)
Just to throw some elaboration out there and potentially help you in the future when the Opacity
property may not be so readily available or is set as immutable. Hope this helps.
ADDENDUM: It's also worth noting that a setting to a property like alpha will always be more performant than setting an opacity to an entire element. This also applies to HTML/CSS scenarios where in something like background-color: rgba(0,0,0,.5)
is better practice than say a <div style="background: black;opacity: .5)
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" />