39

I have a TextBox:

<TextBox x:Name="myTextBox"/>

The TextBox in code behind has two booleans:

 myTextBox.Background.Opacity = 0;
 myTextBox.BorderBrush.Opacity = 0;

Now this is all good and dandy, but how do I set these two properties in XAML?

Btw, setting:

<TextBox x:Name="myTextBox" Background="#00FFFFFF"/>

Does not effect the Opacity property. I'd like to specifically set that opacity property in XAML.

4 Answers 4

85

You want to do something like this:

<TextBlock Text="foo bar">
    <TextBlock.Background>
        <SolidColorBrush Color="Azure" Opacity="0.5" />
    </TextBlock.Background>
</TextBlock>
2
  • This helped me a lot today! This is the solution if you need a different opacity for the foreground and the background.
    – oopbase
    Commented Jun 10, 2014 at 21:52
  • I have been doing this wrong for 10 years! Amazing. Thank you. Commented Apr 17 at 18:26
22

Opacity in XAML is defined as a double, not an HTML color triplet.

http://msdn.microsoft.com/en-us/library/system.windows.uielement.opacity.aspx

You'll want to set it like this:

<TextBlock Opacity="0" />

You can also use a brush to set it:

<SolidColorBrush Color="#FF295564" Opacity="0.3"/>

...and then set the background property to your brush.

4
  • 1
    this is the opacity of the contol, I'm referring the opacity of the background or the border
    – Shai UI
    Commented Oct 12, 2011 at 17:47
  • @foreyez. The second option is setting the opacity for the Brush just as you are programmatically through myTextBox.Background.Opacity. Commented Oct 12, 2011 at 18:15
  • Exactly, using a brush allows you to set either the border opacity or the background. Commented Oct 13, 2011 at 14:16
  • Voted down because zi3guw provided a full XAML example, and opacity alone in the element itself would make the whole element, that is foreground and background, transparent.
    – trapicki
    Commented Jun 24, 2014 at 8:42
7

I don't know when or if this was changed in the past, but at least with WPF 4.5 it's perfectly fine to use 8-digit-hex-color-codes:

<Element Background="#19ff0000"/> // background will be red with an alpha of 10%

The first two digits specify the alpha channel, with 00 (0) beeing fully transparent and FF (255) beeing fully opaque.

3

If you just want a transparent background in XAML there is a Transparent preset:

<Border Background="Transparent"/>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.