如何在WPF网格中设置行边框和背景颜色

21

如何在WPF网格控件中设置边框和背景颜色?
我正在动态创建行和列,并将它们添加到网格中,
我们能否从代码后台设置颜色和边框?

2个回答

46

这是一个看起来很有效的技巧。如果你在通常放置元素的行/列中再加入一个背景元素,它将作为一个背景。只需注意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>

它看起来像这样:

输入图像描述


25

可以通过使用Background属性来设置整个Grid的背景颜色:

<Grid Background="Red" />

如果你想为单个单元格设置背景,你需要向该单元格添加一个具有 Background 属性设置的元素。

至于边框,Grid 只包含 ShowGridLines 属性,该属性可用于显示无法被样式化的细小虚线。

根据 MSDN:

仅提供虚线,因为此属性旨在作为设计工具来调试布局问题,不适用于生产质量代码。如果您想在 Grid 中添加线条,请为 Grid 内部的元素设置边框样式。

因此,要向你的 Grid 添加边框,你必须向 Grid 单元格添加包含 Border 的元素或控件,并对这些元素进行样式设置。

但也有一种替代方案。 这篇博客文章 概述了如何扩展 Grid 类以创建具有 Grid 线条属性的自定义 Grid。当我想要渲染网格线,但不想填充每个单元格时,我曾在过去成功使用过它

<my:CustomGrid ShowCustomGridLines="True"
               GridLineBrush="Blue"
               GridLineThickness="1">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接