wpf - 在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么?

标签 wpf xaml

我有一个网格,里面有一些元素:

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

问题是它看起来很紧:

what i have

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

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

what i want to obtain

最佳答案

您可以将 Margin 放入 Grid.Resources 中的隐式 Style 中。

例如

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

关于wpf - 在 XAML 中设置 Grid 或 StackPanel 元素之间的距离的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11433479/

相关文章:

wpf - 在 WPF 中如何在枚举的情况下定义数据模板?

c# - 如何禁用文本 block ?

c# - XAML 等效于 HTML 标题属性

wpf - 渐变透明系统颜色 (WPF)

c# - 带参数的 XAML 中的自定义 UserControl(按钮)

wpf - 渲染到屏幕外表面时可以使用像素着色器吗?

C# WPF 需要快速缩小包含文本的图像

wpf - WinForms 组件的 WPF 等效项是什么?

c# - 留下下拉组合框会吞噬 WPF 中的焦点

c# - 如何找出谁没有处理事件