WPF: Invert OpacityMask

Posted by Meleak on Stack Overflow See other posts from Stack Overflow or by Meleak
Published on 2010-12-31T16:01:30Z Indexed on 2011/01/01 13:54 UTC
Read the original article Hit count: 369

Filed under:
|
|
|
|

Consider the following piece of Xaml

<Grid Background="Blue">
    <Border Width="100" Height="60" BorderBrush="Black" BorderThickness="2">
        <Border Background="Red">
            <Border.OpacityMask>
                <VisualBrush>
                    <VisualBrush.Visual>
                        <TextBlock Text="Text"
                                   Foreground="#FF000000"
                                   Background="#00000000"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Border.OpacityMask>
        </Border>
    </Border>
</Grid>

It will look like this because of the OpacityMask whos only non-transparent part is the Foreground of the TextBlock.
alt text

Now if I switch the Colors for Foreground and Background in the TextBlock like this

<TextBlock Text="Text"
           Foreground="#00000000"
           Background="#FF000000"/>

I get this because the even though the Foreground is transparent the Background behind it is not, resulting in a useless OpacityMask :)
alt text

Is there anyway I can get this? Basically an inverted OpacityMask
alt text

The reason I'm asking this is because of the answer I made in this question, using the approach from this link. Even though it works, it feels very "hacky".

Am I missing some other way to do this here?

Update
To clarify, even though my example is about a TextBlock, it could be anything. Ellipse/Image/Path etc. The feature I'm after is "Invert OpacityMask"

© Stack Overflow or respective owner

Related posts about wpf

Related posts about xaml