如何在WPF窗口中快速对齐控件?

Csu*_*enő 8 c# wpf

我注意到,与Windows窗体设计器相比,WPF设计器在对齐控件方面做得很差.

在下面的窗口中,我无法对齐每个标签,因此其文本与旁边文本框中的文本位于同一行.第一个标签正确对齐,但WPF设计师没有给我任何快照线来正确对齐第二个和第三个标签.

此外,我无法将按钮与标签对齐.与标签文本相比,快照线将按钮向左放置几个像素.

我无法找到一种快速的方法来手动执行此对齐,也可以编写XAML代码.将控件放在网格中,并设置每个控件的边距非常耗时.

替代文字http://img520.imageshack.us/img520/4843/wpfdesigneralignment.png

您是否知道在WPF窗口中对齐控件的快速方法?

Jus*_*ner 6

使用网格布置控件然后确保控件上没有任何填充...除非你想要一些填充,你确保它们都是均匀的.

快速Google搜索返回了一个基本教程:

WPF网格控件简介

  • +1.使用Canvas进行表单布局实际上是你应该在WPF中做的最后一件事.除非你绝对需要绝对定位控制. (5认同)

Csu*_*enő 4

我认为我可以避免使用手动编码的 XAML 进行对齐。我最终得到的是这样的(样式可以在其他窗口中重用):

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" SizeToContent="WidthAndHeight">
    <Window.Resources>
        <Style x:Key="ControlStyle" TargetType="Control">
            <Setter Property="HorizontalAlignment" Value="Left"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style BasedOn="{StaticResource ControlStyle}" TargetType="Label">
            <Setter Property="Margin" Value="-4,0,0,0"/>
        </Style>
        <Style BasedOn="{StaticResource ControlStyle}" TargetType="TextBox">
            <Setter Property="Width" Value="120"/>
        </Style>
        <Style BasedOn="{StaticResource ControlStyle}" TargetType="Button">
            <Setter Property="MinWidth" Value="70"/>
        </Style>
        <Style TargetType="Grid">
            <Setter Property="Margin" Value="10,10,10,10"/>
        </Style>
        <Style x:Key="SeparatorColumn" TargetType="ColumnDefinition">
            <Setter Property="Width" Value="10"/>
        </Style>
        <Style x:Key="SeparatorRow" TargetType="RowDefinition">
            <Setter Property="Height" Value="3"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Style="{StaticResource SeparatorColumn}"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Style="{StaticResource SeparatorRow}"/>
            <RowDefinition/>
            <RowDefinition Style="{StaticResource SeparatorRow}"/>
            <RowDefinition/>
            <RowDefinition Style="{StaticResource SeparatorRow}"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0">Label:</Label>
        <TextBox Grid.Row="0" Grid.Column="2">TextBox</TextBox>
        <Label Grid.Row="2" Grid.Column="0">Label:</Label>
        <TextBox Grid.Row="2" Grid.Column="2">TextBox</TextBox>
        <Button Grid.Row="4" Grid.ColumnSpan="3">Button</Button>
        <Label Grid.Row="6" Grid.Column="0">Label:</Label>
        <TextBox Grid.Row="6" Grid.Column="2">TextBox</TextBox>
    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)