带有样式和文本块的矩形,内置WPF

Kon*_*che 3 .net c# wpf xaml

我想为矩形创建一个样式或模板.属性非常肤浅:改变了背景颜色,半径.

另外我想在矩形内添加文本.

我找到了很多例子,但没有一个能满足我的需求.是否可以创建一个模板,以我只需要调用的方式绘制矩形和文本

<Rectangle template={StaticRessources myBox}/>
Run Code Online (Sandbox Code Playgroud)

并应用定义的模板?到目前为止,我来了,文本没有在矩形内部对齐:

<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>
Run Code Online (Sandbox Code Playgroud)

对于它的价值,模板应用于一个按钮,但实际上我想将它应用于不起作用的矩形.

Mar*_*ter 5

你需要的是装饰师.已经有一个似乎完全适合你的东西:边框

如果您希望为具有某些预定义值的元素设置重复边框,则可以将其创建为样式:

<Style TargetType="Border" x:Key="MyBorderStyle">
    <Setter Property="Background" Value="Red"/>
    <Setter Property="CornerRadius" Value="3px"/>
</Style>
Run Code Online (Sandbox Code Playgroud)

并应用它:

<Border Style="{StaticResource MyBorderStyle}">
    <TextBlock>Hello World</TextBlock>
</Border>
Run Code Online (Sandbox Code Playgroud)