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

时间:2012-06-28 12:17:07

标签: wpf grid wpf-controls

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

4 个答案:

答案 0 :(得分:33)

这是一个似乎运作良好的黑客攻击。如果在行/列中放置背景元素以及通常放置在那里的元素,它将充当背景。您只需要记住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>

看起来像这样:

enter image description here

答案 1 :(得分:17)

可以使用Background属性为整个Grid设置Background颜色:

<Grid Background="Red" />

或者,如果您希望为单个单元格设置,则需要向已设置Background属性的单元格添加元素。

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

每个MSDN:

  

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

因此,为了向网格添加边框,您必须将包含Border的{​​{1}}元素或控件添加到网格单元格中,并设置这些元素的样式。

但还有另一种选择。 This blog post概述了如何扩展Grid类以创建具有Border行属性的自定义Grid。当我想渲染网格线时,我已经使用过它successfully in the past,但我并不想用对象填充每个单元格。

Grid

答案 2 :(得分:0)

这取决于你打算用这个Grid做什么,但我想你想用控件填充Grid的单元格。

您必须先在控件上设置背景和边框(笔触)属性,或者先将每个控件封装在边框中。

但是,当然如果你想为每个单元格提供相同的背景颜色,那么设置网格的背景。 :)

我希望我的回答很好。

答案 3 :(得分:0)

<Border Grid.Row="12" Grid.Column="0" Grid.ColumnSpan="12" Background="#fff" BorderBrush="Blue" BorderThickness="2"/>