2013-03-26 165 views
16

所有,我對WPF來說是比較新的。我已經搜索了這個答案,但我發現的是如何在運行時而不是列的顏色行;例如以下的問題:在運行時更改整個WPF DataGrid列的背景顏色

  1. Change WPF Datagrid Row Color

  2. How do I programatically change datagrid row color in WPF?

  3. Programmatically assigning a color to a row in DataGrid

  4. Change DataGrid cell colour based on values

等。

我已經看到MSDN DataGrid pages上的CellStyle屬性,但其用途對我來說並不明顯,儘管對此也進行了搜索。

如何在運行時更改整列的背景顏色?

感謝您的時間。

回答

20

我得到它的唯一方法是自己設置列(不使用AutoGenerate)。因此,首先要做的是定義列:

<DataGrid x:Name="Frid" ItemsSource="{Binding Path=.}"> 
     <DataGrid.Columns> 
      <DataGridTextColumn Header="First Name" 
           Binding="{Binding Path=FirstName}"> 

      </DataGridTextColumn> 

      <DataGridTextColumn Header="Last Name" 
           Binding="{Binding Path=LastName}"> 

      </DataGridTextColumn> 
     </DataGrid.Columns> 
    </DataGrid> 

然後,你需要設置每列CellStyle並綁定背景靜態資源,你可以在Window.Resources聲明:

<Window x:Class="WpfApplication1.MainWindow" ...> 
<Window.Resources> 
    <SolidColorBrush x:Key="clBr" Color="White" /> 
</Window.Resources> 
... 

列:

   <DataGridTextColumn Header="First Name" 
            Binding="{Binding Path=FirstName}"> 
       <DataGridTextColumn.CellStyle> 
        <Style TargetType="DataGridCell"> 
         <Setter Property="Background" 
           Value="{StaticResource clBr}" /> 
        </Style> 
       </DataGridTextColumn.CellStyle> 
      </DataGridTextColumn> 

然後你可以通過代碼或xaml操縱來操縱靜態資源。

希望它有幫助。

+0

感謝您的時間,但我想知道如何在運行時執行此操作,因爲我擁有的列是可變的並且在運行時創建。所有最好的... – MoonKnight 2013-03-27 09:02:51

+0

我希望它在運行時完成。我綁定datagrid與窗口load.so數據表如何做? – 2013-04-22 10:56:57

+0

我做了你在答案中指出的,它的工作。但是如何在運行時以編程方式更改它? – Kokombads 2015-02-13 00:59:45

11

有點老了,但這裏是你如何能做到這編程(用於AUTOGEN列):

private void dgvMailingList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) 
{ 
    e.Column.CellStyle = new Style(typeof(DataGridCell)); 
    e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.LightBlue))); 
} 

同樣的方法可以適用於非AUTOGEN列了。

相關問題