Set the stack opacity without affecting child controls

I'm new to WPF, I have a stack panel, and on this stack panel we added a text block to the code behind, and set the glass panel background and the foreground text color Text in the code behind. I also set the opacity dynamically when I set the opacity of the stack panel, than this affects its child control (e.g. Textblock)

Please give me the right solution for this.

Thanks.

+4
source share
5 answers
  • Create a SolidColorBrush for the panel background.

     <!--- in your Window.Resources ---> <SolidColorBrush x:Key="MyTransparentBackground" Color="#334455" Opacity="0.5" /> 

And use it like this

 <StackPanel Background="{StaticResource MyTransparentBackground}"> <Label Content="Hello there" FontWeight="Bold" FontSize="20" VerticalAlignment="Center" HorizontalAlignment="Center"></Label> </StackPanel> 
-5
source

If you want to do this in Xaml , you can create a SolidColorBrush on your Window.Resources to be the background color of the panel:

 <Window.Resources> <SolidColorBrush x:Key="TransparentBlue" Color="#00b0f0" Opacity="0.5" /> </Window.Resources> 

And then set only the Background your ...Panel :

 <StackPanel Background="{StaticResource TransparentBlue}"> <Label Content="Hello there" FontWeight="Bold" FontSize="20" VerticalAlignment="Center" HorizontalAlignment="Center"></Label> </StackPanel> 
+21
source

Set the Background property to mutable Brush (instead of the immutable Brushes.White type). For example, you can create a SolidColorBrush :

 var background = new SolidColorBrush(Colors.White); panel.Background = background; 

Now you can change the Opacity property of this brush in your program.

 background.Opacity = 0.5; 

You can also do this with any other brush, like GradientBrush or ImageBrush , etc.

+1
source

Read the Notes UIElement.Opacity Property

Opacity applies from parent elements down the element tree to children, but the visible effects of nested opacity parameters are not specified in the property value of the individual children. For example, if a list has 50% (0.5) opacity and one of its list items has its own opacity of 20% (0.2), visible transparency because this list item will be displayed as if it were 10% (0 , 1), but the value of the property of the list item Opacity property will be 0.2 when prompted.

The child control cannot have more opacity than the parent. I think you will have to use two separate layers: one with full opacity and one with less. Something like that

 <Grid> <StackPanel Opacity=".5" Background="whatever"> ... </StackPanel> <StackPanel> <TextBlock Text="Text shown with full Opacity" /> </StackPanel> </Grid> 
0
source

This worked for me in Xamarin (white transparent color):

 Color MyColor = Color.FromRgba(255,255,255,0.8); 

Alpha seems to give better opacity than the opacity property of controls.

0
source

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


All Articles