开发者

Rectangle with style and text block inside with WPF

开发者 https://www.devze.com 2023-02-18 21:22 出处:网络
I would like to create a style or template for rectangles. The properties are quite superficial: changed background color, radius.

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">
      开发者_JS百科  <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.


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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号