Search code examples
uwpbordertextblock

Provide Border to TextBlock in UWP


How can I add a border to TextBlock without wrapping it with any extra framework element? One approach I have tried is by wrapping TextBlock with Border but I don't want to add an extra UI element like a border.


Solution

  • OK, firstly, deeply nested elements isn't something to avoid unless you have specific issues. However, the most performant way of doing this is to overlay a transparent rectangle onto the TextBlock inside a Grid, like this:

    <Grid HorizontalAlignment="Left" VerticalAlignment="Top">
        <TextBlock Text="This is a textblock" 
                   Margin="3" 
                   HorizontalAlignment="Left" 
                   VerticalAlignment="Top" />
        <Rectangle Stroke="Black" 
                   StrokeThickness="1" 
                   Fill="Transparent" 
                   HorizontalAlignment="Stretch" 
                   VerticalAlignment="Stretch"/>
    </Grid>
    

    enter image description here