首页 > 解决方案 > 按钮模板 - 在矩形上添加网格

问题描述

这是我在 XAML 代码中的按钮模板:

<Window.Resources>
    <ControlTemplate x:Key="templateOfButton" TargetType="Button">
        <Rectangle Height="200" Width="200">
            <Rectangle.Fill>
                <ImageBrush ImageSource="kot.jpg"/>
            </Rectangle.Fill>
        </Rectangle>
    </ControlTemplate>
</Window.Resources>

目前,只有一个用 Image 填充的矩形。我想在这个矩形上添加网格,所以我不仅可以使用 Image 填充它,还可以将 Image放在矩形上,并在适当的列/行中添加另一个对象,如 Textblocks。有谁知道如何做到这一点?可能吗?

我认为这张照片解释了我想做的事情:链接

标签: c#wpf

解决方案


这是一个可以应用于 Button 的 ControlTemplate,它可以执行图片中显示的操作:

<ControlTemplate x:Key="templateOfButton" TargetType="Button">
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <Image Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"/>
    <TextBlock Grid.Column="1" Grid.Row="0" Text="1" />
    <TextBlock Grid.Column="1" Grid.Row="1" Text="2" />
    <TextBlock Grid.Column="1" Grid.Row="2" Text="3" />
  </Grid>
</ControlTemplate>

推荐阅读