Konrad Reiche
Konrad Reiche

Reputation: 29493

Rectangle with style and text block inside with WPF

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

In addition I would like to add text inside of the rectangle.

I've found alot of examples, but none fit my needs the best. Is it possible to create a template drawing the rectangle and text inside in a way I only need to call

<Rectangle template={StaticRessources myBox}/>

And the defined template is applied? So far I came, 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 is applied to a button, but actually I want to apply it to rectangle which does not work.

Upvotes: 3

Views: 11319

Answers (1)

Markus H&#252;tter
Markus H&#252;tter

Reputation: 7906

What you need is a Decorator. There is one already that seems like to fit for you perfectly: Border

if you want to have a recurring border for elements with some predefined values you can create as Style like:

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

and apply it like:

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

Upvotes: 5

Related Questions