0

A VisualBrush is used to fill a Rectangle in a WPF window.

It fills by binding its Visual property to a non-transparent element in the window.

How can the Rectangle fill be made transparent, so that what is behind the window is visible through it, without making other elements transparent as well?

Roughly following the how-to on creating reflection effects on MSDN, and looking at SO questions about making specific elements opaque with a transparent window here and here, I've come up with the following in XAML. However, I cannot seem to make the Rectangle transparent, without also making the TextBlock it is bound to also transparent.

<!-- Window.AllowsTransparency is set to true,
    so WindowStyle must also be set to None.
    Background is set to Transparent so child
    elements have capability to be transparent
    to what is behind the window. -->

<Window x:Class="XAMLViewTests.TransparentTestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TransparentTestWindow"
        AllowsTransparency="True"
        WindowStyle="None" Background="Transparent">
    <StackPanel Orientation="Vertical">

        <!-- Two elements: TextBlock and Rectangle -->

        <TextBlock x:Name="textBlock" Background="White">This is some text.</TextBlock>

        <Rectangle Height="{Binding ElementName=textBlock, Path=ActualHeight}">
            <!-- Fill rectangle with a Visual element bound to TextBlock,
            so it shows exactly the same as TextBlock. Transforms, effects, etc
            can now be performed on the Visual. -->

            <Rectangle.Fill>
                <VisualBrush Stretch="None" Visual="{Binding ElementName=textBlock}">
                </VisualBrush>
            </Rectangle.Fill>
        </Rectangle>
    </StackPanel>
</Window>
Community
  • 1
  • 1
Aaron Thomas
  • 5,054
  • 8
  • 43
  • 89

1 Answers1

0

You cannot set the textblock as background and make its background transparent just for the binding.

What you can do though is setting another textblock as background and bind all relevant values to the original textblock:

<Rectangle.Fill>
    <VisualBrush Stretch="None">
        <VisualBrush.Visual>
            <TextBlock Background="Transparent" 
                        Text="{Binding ElementName=textBlock, Path=Text}" 
                        Width="{Binding ElementName=textBlock, Path=ActualWidth}" />
        </VisualBrush.Visual>
    </VisualBrush>
</Rectangle.Fill>
Domysee
  • 12,718
  • 10
  • 53
  • 84