如何在WPF网格控件中设置边框和背景颜色,
我动态地创建行和列,然后添加到网格中,
我们可以从后面的代码中设置颜色和边框吗?
发布于 2012-06-28 20:51:03
可以使用Background属性为整个Grid设置Background颜色:
<Grid Background="Red" />或者,如果希望为单个单元格设置该属性,则需要向设置了Background属性的单元格添加一个元素。
至于边框,Grid只包含ShowGridLines属性,该属性可用于显示无法设置样式的细虚线。
每个MSDN:
仅虚线可用,因为此属性旨在用作调试布局问题的设计工具,而不是用于产品质量代码。如果要在网格中使用线条,请将网格中的元素设置为具有边框。
因此,为了向网格添加边框,您必须向网格单元格添加包含Border的Border元素或控件,并设置这些元素的样式。
但还有另一种选择。This blog post概述了如何扩展网格类以创建具有Grid线条属性的自定义网格。当我想渲染网格线,但又不想用对象填充每个单元格时,我就用它successfully in the past了。
<my:CustomGrid ShowCustomGridLines="True"
GridLineBrush="Blue"
GridLineThickness="1">发布于 2013-09-24 03:15:02
这是一个似乎运行良好的小技巧。如果在行/列中放置背景元素以及通常放置在那里的元素,则它将充当背景。您只需要注意XAML中元素的顺序(元素按Z顺序递增),或者相应地设置Panel.Zorder。
<Window x:Class="gridBackground.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Border Background="Red" />
<Border Grid.Row="2" Grid.Column="1" Background="Red" />
<Border Grid.Row="1" Background="LightBlue" />
<Border Grid.Row="2" Background="Orange" />
<Border Grid.Row="0" Grid.Column="1" Background="Orange" />
<TextBlock Grid.ColumnSpan="2" Grid.Row="1" Text="Here is some more text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Grid.ColumnSpan="2" Text="Here is some text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Grid.ColumnSpan="2" Grid.Row="2" Text="Here is even more text" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>它看起来是这样的:

https://stackoverflow.com/questions/11244457
复制相似问题