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

Buz*_*uzz 17 wpf grid wpf-controls

我们如何在WPF网格控件中设置边框和背景颜色,
我动态创建行和列然后添加到网格,
我们可以从后面的代码设置颜色和边框吗?

Chr*_*ott 35

这是一个似乎运作良好的黑客攻击.如果在行/列中放置背景元素以及通常放置在那里的元素,它将作为背景.您只需要记住XAML中元素的排序(元素出现在增加的Z-Order中),或者相应地设置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>
Run Code Online (Sandbox Code Playgroud)

它看起来像这样:

在此输入图像描述


Rac*_*hel 18

Background颜色正好可以为整个组Grid通过使用Background属性:

<Grid Background="Red" />
Run Code Online (Sandbox Code Playgroud)

或者,如果您希望为单个单元格设置,则需要向具有其Background属性集的单元格添加元素.

至于Borders,Grid只包含ShowGridLines属性,可用于显示无法设置样式的细虚线.

每个MSDN:

只有虚线可用,因为此属性旨在用作调试布局问题的设计工具,不适用于生产质量代码.如果您想要网格内的线条,请将网格中的元素设置为具有边框.

因此,为了向Grid添加边框,您必须向Grid单元格添加Border包含a的元素或控件Border,并设置这些元素的样式.

但还有另一种选择.本博文概述了如何扩展Grid类以创建具有Grid行属性的自定义Grid .我曾经成功地使用它,当我想渲染网格线,但不想用对象填充每个单元格.

<my:CustomGrid ShowCustomGridLines="True"
               GridLineBrush="Blue"
               GridLineThickness="1">
Run Code Online (Sandbox Code Playgroud)