Unpredictable Opacity Behavior in WPF Fonts

I have a problem with understanding opacity in WPF. I have the code below. My questions:

  • Why do the rectangle and font have different colors?
  • Why do both TextBlocks get different colors when I change the font size?

I would expect that when I close the color using the color set, black with an opacity of 50% will display # 7F7F7F, but instead I get # C2C2C2 for a smaller TextBlock and the expected # 7F7F7F for a larger font and a rectangle.

The question was partially asked at https://github.com/ButchersBoy/MaterialDesignInXamlToolkit/issues/408 , but did not receive a proper answer.

Any help is appreciated!

The code:

<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>
+6
1

, TextBlock. , , , , StackPanel.

<TextBlock Text="Click me" HorizontalAlignment="Center" Style="{StaticResource TextBlockStyle}" Opacity="0.5"/>

ControlTemplate .

TextBlock, TextBlock, , .

+1

Source: https://habr.com/ru/post/1015708/


All Articles