WPF教程(二十八)Grid

本文介绍了 WPF 中 Grid 面板的基本用法,包括如何定义列和行,以及如何设置按钮等控件的位置。展示了如何利用 Grid 的 ColumnDefinitions 和 RowDefinitions 实现控件的精确布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Grid面板也许是最复杂的面板类型了。Grip可以包含多行多列。你可以定义每一行的高度和每一列的宽度,通过一个像素值、可用空间的百分比或者自动分配这三种方式。自动分配会根据内容自动调整行高和列宽。Grip一般用于其他面板无法实现的情形,譬如如你需要很多列而且需要联合其他面板。

在Grid中的所有控件都会被最大化,同时一个叠一个放置。这是Grid最基本的形式。

<Window x:Class="WpfTutorialSamples.Panels.Grid"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid" Height="300" Width="300">
    <Grid>
                <Button>Button 1</Button>
                <Button>Button 2</Button>
        </Grid>
</Window>
A simple Grid
如上所示,第二个按钮占据了顶部的位置,于是就看不到第一个按钮了。这个场景基本不会用到,因此我们来划分区域,这正是Grid擅长的。我们使用ColumnDefinitions和RowDefinitions来实现。
<Window x:Class="WpfTutorialSamples.Panels.Grid"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid" Height="300" Width="300">
    <Grid>
                <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>
                <Button>Button 1</Button>
                <Button Grid.Column="1">Button 2</Button>
        </Grid>
</Window>

A Grid divided into two columns

在这个例子,我们将空间划分成相等的两列,宽度使用一个“*”。第二个按钮中,我使用了一个附加属性来使其置于第二列(0是第一列,1是第二列)。也可以把这个附加属性加在第一个按钮上,但是,第一个按钮被自动分配到第一列去了。

两个按钮占据了整个可用空间,这是Grid在排列其子控件时默认的形式。这是通过设置HorizontalAlignment和VerticalAlignment来实现的。

某些场景下,你希望控件只占据其所需的空间,或者控制它们在Gird中的位置。最简单的办法就是给你要操作的控件设置HorizontalAlignment和VerticalAlignment。以下是上例的升级版:

<Window x:Class="WpfTutorialSamples.Panels.Grid"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Grid" Height="300" Width="300">
    <Grid>
                <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>               
                <Button VerticalAlignment="Top" HorizontalAlignment="Center">Button 1</Button>
                <Button Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Right">Button 2</Button>
        </Grid>
</Window>
A Grid divided into two columns with custom alignment on the child controls
从截屏可以看到,在第一列中,第一个按钮被放置到顶部并居中的位置;在地儿列中,第二个按钮被放置到靠右并居中的位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值