在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么? [英] What is the best way to set a distance between Grid's or StackPanel's elements in XAML?

查看:88
本文介绍了在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些元素的网格:

I have a Grid with some elements inside:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <TextBlock Text="SomeText" Grid.Column="0" Grid.Row="0" />
    <TextBox Grid.Column="1" Grid.Row="0" />

    <TextBlock Text="SomeText" Grid.Column="0" Grid.Row="1" />
    <TextBox Grid.Column="1" Grid.Row="1" />

    <TextBlock Text="SomeText" Grid.Column="0" Grid.Row="2" />
    <TextBox Grid.Column="1" Grid.Row="2" />
</Grid>

问题在于它看起来很紧:

The problem is that it looks tightly:

我有什么

Margin 属性解决了这个问题,但是我应该为网格内的每个元素设置这个属性.这是一条艰难的道路.

Margin property solves this problem, but I should to set this property to each element inside a grid. It is a hard way.

我只想获得一次这样的设置 margin 属性,但不是每个元素:

I want to obtain something like this setting margin property only once, but not for each element:

我想获得什么

推荐答案

您可以将 Margin 放入 Grid.Resources 中的隐式 Style代码>.

You can put the Margin into an implicit Style in the Grid.Resources.

例如

<Style x:Key="MarginStyle" TargetType="FrameworkElement">
     <Setter Property="Margin" Value="5"/>
</Style>
<Style TargetType="TextBox" BasedOn="{StaticResource MarginStyle}"/>
<Style TargetType="TextBlock" BasedOn="{StaticResource MarginStyle}"/>

<小时>

您还可以使用 ItemsControl 来应用通用样式.

例如

<ItemsControl>
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <!-- Panel without children here -->
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition/>
          <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
      </Grid>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
  <ItemsControl.ItemContainerStyle>
    <Style TargetType="FrameworkElement">
      <Setter Property="Margin" Value="5"/>
    </Style>
  </ItemsControl.ItemContainerStyle>
  <!-- Children here -->
  <Label Grid.Row="0" Content="Field 1: "/>
  <Label Grid.Row="1" Content="Field 2: "/>
  <TextBox Grid.Column="1" Grid.Row="0"/>
  <TextBox Grid.Column="1" Grid.Row="1"/>
</ItemsControl>

这篇关于在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆