2012-06-28 89 views

回答

12

Background顏色正好可以爲整個Grid使用Background屬性設置:

<Grid Background="Red" /> 

或者,如果你想將其設置爲單個細胞,你需要的元素添加到具有細胞的Background屬性集。

至於邊界,Grid只包含ShowGridLines屬性,它可以用來顯示無法設置樣式的細虛線。

每MSDN:

只因爲這個屬性的目的是作爲一個 設計工具來調試佈局問題,而不是用於在 生產質量的代碼使用虛線是可用的。如果您需要網格內的線條,請在網格中設置 元素以具有邊框。

因此,爲了邊框添加到您的網格,你必須添加Border元素或含有Border到網格單元的控制,和風格的元素。

但有一個選擇。 This blog post概述瞭如何擴展Grid類以創建具有Grid行屬性的自定義Grid。當我想渲染網格線時,我已經使用它successfully in the past,但不想用對象填充每個單元格。

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

這取決於你打算如何使用這個網格,但我想你想用控件填充網格的單元格。

您將不得不在控件上設置背景和邊框(Stroke)屬性,或者先將每個控件封裝在邊框中。

但是,當然如果你想爲每個單元格設置相同的背景顏色,那麼設置網格的背景。 :)

我希望我的回答很好。

27

這是一個似乎工作得很好的黑客。如果您將背景元素與通常放置在那裏的元素一起放入行/列中,它將作爲背景。您只需要介意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