2013-03-26 167 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列了。

相关问题