I have a problem understanding opacity in WPF. I have the code posted below. My questions are:
I would expect that, when I snoop the color with a color picker, black with an opacity with 50% would render #7F7F7F, but instead I get #C2C2C2 for the smaller TextBlock, and the expected #7F7F7F for the larger font and the rectangle.
Question has been partially asked at https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/issues/408 but not properly answered.
Any help is appreciated!
The code is:
<Window x:Class="WpfPlay.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfPlay"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="800" Background="White">
<Window.Resources>
<SolidColorBrush x:Key="ForeBrush" Color="Black" Opacity="0.5"/>
<SolidColorBrush x:Key="BackBrush" Color="White" Opacity="1.0"/>
<Style TargetType="TextBlock" x:Key="TextBlockStyle">
<Setter Property="Foreground" Value="{StaticResource ForeBrush}"/>
<Setter Property="Background" Value="{StaticResource BackBrush}"/>
<Setter Property="FontSize" Value="48"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
<Style TargetType="TextBlock" x:Key="TextBlockLargeStyle">
<Setter Property="Foreground" Value="{StaticResource ForeBrush}"/>
<Setter Property="Background" Value="{StaticResource BackBrush}"/>
<Setter Property="FontSize" Value="100"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</Window.Resources>
<StackPanel Orientation="Vertical" Background="White">
<TextBlock Text="Click me" HorizontalAlignment="Center" Style="{StaticResource TextBlockStyle}" Margin="20"/>
<TextBlock Text="Click me" HorizontalAlignment="Center" Style="{StaticResource TextBlockLargeStyle}" Margin="20"/>
<Rectangle Width="100" Height="100" HorizontalAlignment="Center" Margin="20" Fill="{StaticResource ForeBrush}"/>
</StackPanel>
</Window>
You could use a workaround by setting the opacity on the complete TextBlock. This would of course also change the opacity of the backbrush, so it may not give the desired effect if you have a different StackPanel back color.
<TextBlock Text="Click me" HorizontalAlignment="Center" Style="{StaticResource TextBlockStyle}" Opacity="0.5"/>
But there is also the possibility to overwrite the ControlTemplate of a textblock and connect the opacity property to the foreground only.
Or you could make a Grid with inside a TextBlock, so you can set the opacity property on the TextBlock without touching the background of the rectangle it is sitting in.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With