I need transparent text with opaque background with WPF/XAML. Is that possible?
Here is an example, but I don\'t use css: css, transparent text with opaque background
You can set it using the Opacity
property on the SolidColorBrush
. It takes values from 0 to 1. Where 0
is complete transparency and 1
complete opacity. But if you set the text transparent then what you will see is the background of the text box. In the example I've set partial opacity so you can see the text is greyish.
<TextBlock Text="Test" Background="Red" Width="100" Height="100">
<TextBlock.Foreground>
<SolidColorBrush Opacity="0.25" Color="Black"/>
</TextBlock.Foreground>
</TextBlock>
Other thing to get the transparency and see the background of the control beneath the text block is to set transparent foreground and partially transparent background.
U can make this by converting your text to Path
and then Make Clipping
On your white Rectangle
with that Path
.
Try this:
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox x:Name="textToMask" TextChanged="textToMask_TextChanged" />
<Rectangle Grid.Row="1" x:Name="target" Fill="Yellow"/>
</Grid>
c# code
private void textToMask_TextChanged(object sender, TextChangedEventArgs e)
{
Typeface face = new Typeface("Candara");
FormattedText tx = new FormattedText(textToMask.Text, Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight, face, 70, Brushes.Black);
Geometry textGeom = tx.BuildGeometry(new Point(0, 0));
Rect boundingRect = new Rect(new Point(-100000, -100000), new Point(100000, 100000));
RectangleGeometry boundingGeom = new RectangleGeometry(boundingRect);
GeometryGroup group = new GeometryGroup();
group.Children.Add(boundingGeom);
group.Children.Add(textGeom);
target.Clip = group;
}