wpfxamlbackgroundtextblockvisualbrush

TextBlock Background Property removing stretch


I have a TextBox defined as this:

<TextBox>
    <TextBox.Background>
        <VisualBrush>
            <VisualBrush.Visual>
                <StackPanel>
                    <TextBlock Background="Blue" Opacity="0.5" Text="155"/>
                </StackPanel>
            </VisualBrush.Visual>
        </VisualBrush>
    </TextBox.Background>
</TextBox>

It looks like this:

enter image description here

However, when I remove the Background property, the text stretches like this:

enter image description here

Is there any way to add the background without changing the way the text looks?


Solution

  • a workarround of this problem which i don't know why it occurs would be to remove Background property from textblock and put it behind it like this

            <Grid>
                <Rectangle Fill="Blue"/>
                <TextBox Height="100">
                    <TextBox.Background>
                        <VisualBrush Stretch="Fill" TileMode="None" AlignmentX="Left" AlignmentY="Top">
                            <VisualBrush.Visual>
                                <StackPanel>
                                    <TextBlock Margin="0" Padding="0" Opacity="0.5" Text="155"/>
                                </StackPanel>
    
                            </VisualBrush.Visual>
                        </VisualBrush>
                    </TextBox.Background>
                </TextBox>
            </Grid>