Интервал между дочерними элементами управления в сетке WPF - PullRequest
55 голосов
/ 22 мая 2009

У меня есть набор пар ключ / значение, которые я хочу отобразить в окне WPF. Я использую сетку, чтобы выложить их так:

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

    <Label Grid.Row="0" Grid.Column="0">Code</Label>
    <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Code}"/>

    <Label Grid.Row="1" Grid.Column="0">Name</Label>
    <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}"/>
</Grid>

Однако, когда я отображаю это, текстовые поля сжимаются так, чтобы их верхняя и нижняя границы касались текстового поля выше / ниже. Каков наилучший способ добавить вертикальное пространство к строкам в этом макете?

Ответы [ 3 ]

82 голосов
/ 22 мая 2009

Самый простой способ - установить маржу для отдельных элементов управления. Установка его в TextBox должна быть достаточной, потому что как только они разнесены, метки будут располагаться вертикально в центре каждой строки и все равно будут иметь достаточно места.

Вы можете установить его один раз, используя стиль:

<Grid Margin="4">
    <Grid.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Margin" Value="0,0,0,4" />
        </Style>
    </Grid.Resources>

    ...
</Grid>

Это добавит 4-пиксельное поле к нижней части любого текстового поля внутри вашей сетки.

49 голосов
/ 30 мая 2011

Другой хороший подход можно увидеть здесь .

Вы создаете класс для установки Margin свойство:

public class MarginSetter
{
    public static Thickness GetMargin(DependencyObject obj) => (Thickness)obj.GetValue(MarginProperty);

    public static void SetMargin(DependencyObject obj, Thickness value) => obj.SetValue(MarginProperty, value);

    // Using a DependencyProperty as the backing store for Margin. This enables animation, styling, binding, etc…
    public static readonly DependencyProperty MarginProperty =
        DependencyProperty.RegisterAttached(nameof(FrameworkElement.Margin), typeof(Thickness),
            typeof(MarginSetter), new UIPropertyMetadata(new Thickness(), MarginChangedCallback));

    public static void MarginChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        // Make sure this is put on a panel
        var panel = sender as Panel;

        if (panel == null) return;

        panel.Loaded += Panel_Loaded;
    }

    private static void Panel_Loaded(object sender, EventArgs e)
    {
        var panel = sender as Panel;

        // Go over the children and set margin for them:
        foreach (FrameworkElement fe in panel.Children.OfType<FrameworkElement>())
            fe.Margin = GetMargin(panel);
    }
}

Теперь вы добавили свойство свойства, чтобы синтаксис работал следующим образом:

<StackPanel local:MarginSetter.Margin="5">
   <TextBox Text="hello" />
   <Button Content="hello" />
   <Button Content="hello" />
</StackPanel>

Это самый простой и быстрый способ задать Margin нескольким дочерним элементам панели, даже если они не одного типа. (Т. Е. Button с, TextBox с, ComboBox с, и т. Д.)

2 голосов
/ 07 февраля 2014

Как насчет установки вертикального выравнивания TextBox в центр?

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

                <Label Grid.Row="0" Grid.Column="0">Code</Label>
                <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Code}" VerticalAlignment="Center"/>

                <Label Grid.Row="1" Grid.Column="0">Name</Label>
                <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center"/>
            </Grid>
...