1.HorizontalAlignment
HorizontalAlignment属性用来确定控件在其父容器中的水平位置。可以使用以下值:Left(靠左)、Right(靠右)、Center(居中)、Stretch(填充父容器的剩余空间)等。
2.VerticalAlignment
VerticalAlignment属性用来确定控件在其父容器中的垂直位置。可以使用以下值:Top(靠上)、Bottom(靠下)、Center(居中)、Stretch(填充父容器的剩余空间)等。
3.应用
<Grid><ButtonHorizontalAlignment="Center"VerticalAlignment="Center"Background="LightGray"Content="CenterCenter"/><ButtonHorizontalAlignment="Left"VerticalAlignment="Top"Background="LightGray"Content="LeftTop"/><ButtonHorizontalAlignment="Left"VerticalAlignment="Center"Background="LightGray"Content="LeftCenter"/><ButtonHorizontalAlignment="Left"VerticalAlignment="Bottom"Background="LightGray"Content="LeftBottom"/><ButtonHorizontalAlignment="Center"VerticalAlignment="Top"Background="LightGray"Content="TopCenter"/><ButtonHorizontalAlignment="Center"VerticalAlignment="Bottom"Background="LightGray"Content="TopCenter"/><ButtonHorizontalAlignment="Right"VerticalAlignment="Center"Background="LightGray"Content="TopCenter"/><ButtonHorizontalAlignment="Right"VerticalAlignment="Top"Background="LightGray"Content="TopCenter"/><ButtonHorizontalAlignment="Right"VerticalAlignment="Bottom"Background="LightGray"Content="TopCenter"/></Grid>
4.Stretch
如果您想要实现按钮内容填充父容器中的剩余空间,可以考虑使用其他布局控件,比如Grid或者StackPanel,并将按钮设置为该控件的子元素。您可以通过设置子元素的HorizontalAlignment和VerticalAlignment属性来控制子元素填充父容器的方式。
将按钮放在一个Grid控件中,将按钮的HorizontalAlignment和VerticalAlignment属性设置为Stretch,按钮将会填充Grid的整个空间。同时,将Grid的大小设置为父容器的大小,实现了按钮内容填充父容器的效果。
- 子控件填充父空间
<GridWidth="400"Height="200"Background="LightGray"><Grid.RowDefinitions><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinitionWidth="100"/></Grid.ColumnDefinitions><ButtonWidth="auto"Height="auto"HorizontalAlignment="Stretch"VerticalAlignment="Stretch"Background="LightBlue"Content="按钮"/></Grid>
- 控件模板内的内容填充控件
<GridWidth="400"Height="200"Background="LightGray"><Grid.RowDefinitions><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition/></Grid.ColumnDefinitions><ButtonWidth="Auto"Height="Auto"HorizontalAlignment="Stretch"VerticalAlignment="Stretch"BorderBrush="Transparent"><Button.Template><ControlTemplateTargetType="Button"><BorderBackground="{TemplateBinding Background}"BorderBrush="{TemplateBinding BorderBrush}"BorderThickness="{TemplateBinding BorderThickness}"><ContentPresenterHorizontalAlignment="Stretch"VerticalAlignment="Stretch"/></Border></ControlTemplate></Button.Template><TextBlockHorizontalAlignment="Center"VerticalAlignment="Center"Text="按钮"/></Button></Grid>