WPF绘制表格

WPF的Grid布局使用起来很方便,但如果我想绘制一个带有边线的表格则显得有点儿力不从心。虽然Grid有ShowGridLines这个bool类型的属性,但此属性设为true时显示的虚线而且不能改变颜色。比如下面的代码:

<Window x:Class="Table.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Table" Height="350" Width="525">
    <Grid ShowGridLines="True">
        <Grid.RowDefinitions>
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
    </Grid>
</Window>

效果图如下:
在这里插入图片描述
那么,如何让Grid“作table状”呢?
使用Border控件
使用Border的BorderThickness属性可以控制Border各边的显隐粗细(粗细为0就是不显示)。使用BorderBrush属性则可灵活控制每个单元格的边线颜色。看下面的代码:

<Window x:Class="Table.Table"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Table_1" Height="300" Width="300">
    <Grid ShowGridLines="False">
        <Grid.RowDefinitions>
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Border BorderBrush="Black" BorderThickness="1" Grid.Column="0" Grid.Row="0"/>
        <Border BorderBrush="Blue" BorderThickness="0,1,1,1" Grid.Column="1" Grid.Row="0" Grid.ColumnSpan="2"/>
        <Border BorderBrush="Red" BorderThickness="1,0,1,1" Grid.Column="0" Grid.Row="1"/>
        <Border BorderBrush="Orange" BorderThickness="0,0,1,1" Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="2"/>
        <Border BorderBrush="Lime" BorderThickness="1,0,1,1" Grid.Column="0" Grid.Row="2" Grid.ColumnSpan="2" Grid.RowSpan="2"/>
    </Grid>
</Window>

效果图如下:
在这里插入图片描述
最后提醒一点,如果是大批量的绘制表格那么这种手动写代码的方式就划不来了。应该使用DataTemplate来显示数据,在DataTemplate里恰当地使用Border并为其BorderThickness和Column/Row/ColumnSpan/RowSpan设置恰当的Binding。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值