WPF绘制表格
作者:互联网
开发工具与关键技术:WPF绘制表格
作者:李哲定
撰写时间:2021年10月28日
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>
效果图如下: ![在这里插入图片描述](https://www.icode9.com/i/ll/?i=5a1ac03ad3d2432eb658ab2f44b161c4.png#pic_center)
那么,如何让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>
![在这里插入图片描述](https://www.icode9.com/i/ll/?i=94a6aa2945884ea49bb2adc7bf616e37.png?,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5Lmd57q45oOF5Lmmwrc=,size_10,color_FFFFFF,t_70,g_se,x_16#pic_center) 最后提醒一点,如果是大批量的绘制表格那么这种手动写代码的方式就划不来了。应该使用DataTemplate来显示数据,在DataTemplate里恰当地使用Border并为其BorderThickness和Column/Row/ColumnSpan/RowSpan设置恰当的Binding。
标签:xmlns,http,表格,绘制,xaml,winfx,WPF,Border,schemas 来源: https://blog.csdn.net/qq_39828828/article/details/121014200