Rectangle with style and text block inside with WPF
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>
Konrad Reiche
Updated on June 04, 2022Comments
-
Konrad Reiche almost 2 years
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.