Rectangle with style and text block inside with WPF

I would like to create a style or pattern for rectangles. The properties are quite superficial: changed background color, radius.

Also, I would like to add text inside the rectangle.

I found many examples, but none of them matched my needs. Is it possible to create a template that draws a rectangle and text inside the way I only need to call

<Rectangle template={StaticRessources myBox}/>

And does a specific pattern apply? Until I arrived, the text is not aligned inside the rectangle:

<ControlTemplate x:Key="greenBoxTemplate">
        <Grid>
            <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="25" Text="Hello World" TextWrapping="Wrap"/>
            <Rectangle Height="100" HorizontalAlignment="Left" Margin="233,144,0,0" Name="BNU2" Style="{StaticResource greenBox}" Stroke="Black" VerticalAlignment="Top" Width="200"/>
        </Grid>
    </ControlTemplate>

For what it's worth, the template applies to the button, but actually I want to apply it to a rectangle that doesn't work.

+3
source share
1 answer

Decorator. , , , : Border

, , :

<Style TargetType="Border" x:Key="MyBorderStyle">
    <Setter Property="Background" Value="Red"/>
    <Setter Property="CornerRadius" Value="3px"/>
</Style>

:

<Border Style="{StaticResource MyBorderStyle}">
    <TextBlock>Hello World</TextBlock>
</Border>
+4

All Articles