以编程方式为DataGrid中的行分配颜色

问题描述:

我需要为我在运行时添加到DataTable的行分配颜色。如何才能做到这一点?以编程方式为DataGrid中的行分配颜色

您可以处理DataGrid的LoadingRow事件以检测何时添加行。在事件处理程序中,您可以获取DataRow的引用,该引用已添加到充当您的ItemsSource的DataTable中。然后,您可以更新DataGridRow的颜色,只要你喜欢。

void dataGrid_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e) 
{ 
    // Get the DataRow corresponding to the DataGridRow that is loading. 
    DataRowView item = e.Row.Item as DataRowView; 
    if (item != null) 
    { 
     DataRow row = item.Row; 

      // Access cell values values if needed... 
      // var colValue = row["ColumnName1]"; 
      // var colValue2 = row["ColumName2]"; 

     // Set the background color of the DataGrid row based on whatever data you like from 
     // the row. 
     e.Row.Background = new SolidColorBrush(Colors.BlanchedAlmond); 
    }   
} 

要注册的事件在XAML:

<toolkit:DataGrid x:Name="dataGrid" 
    ... 
    LoadingRow="dataGrid_LoadingRow"> 

或者在C#:

this.dataGrid.LoadingRow += new EventHandler<Microsoft.Windows.Controls.DataGridRowEventArgs>(dataGrid_LoadingRow); 
+0

保证分配默认值行的颜色不是由条件 – 2010-01-17 02:53:09

+0

谢谢。这对我来说是一个惊人的简单方法。 – Nasenbaer 2011-08-11 14:40:51

+0

不起作用。项目始终为空 – Yusha 2017-12-29 21:18:18

重要:一定要始终指定默认值不在行被一种条件或任何其他风格着色。

查看我的回答C# Silverlight Datagrid - Row Color Change

PS。我在Silverlight并没有证实在WPF

这种行为

U可以试试这个

在XAML

<Window.Resources> 
<Style TargetType="{x:Type DataGridRow}"> 
    <Style.Setters> 
     <Setter Property="Background" Value="{Binding Path=StatusColor}"></Setter> 
    </Style.Setters>    
</Style> 
</Window.Resources> 

在DataGrid

<DataGrid AutoGenerateColumns="False" CanUserAddRows="False" Name="dtgTestColor" ItemsSource="{Binding}" > 
<DataGrid.Columns>        
    <DataGridTextColumn Header="Valor" Binding="{Binding Path=Valor}"/> 
</DataGrid.Columns> 
</DataGrid> 

在代码中,我有一类

public class ColorRenglon 
{ 
    public string Valor { get; set; } 
    public string StatusColor { get; set; } 
} 

当设置在DataContext

dtgTestColor.DataContext = ColorRenglon; 
dtgTestColor.Items.Refresh(); 

如果妳不设置行的默认值是灰色

的颜色

ü可以试试这个样本 这个样本

List<ColorRenglon> test = new List<ColorRenglon>(); 
ColorRenglon cambiandoColor = new ColorRenglon(); 
cambiandoColor.Valor = "Aqui va un color"; 
cambiandoColor.StatusColor = "Red"; 
test.Add(cambiandoColor); 
cambiandoColor = new ColorRenglon(); 
cambiandoColor.Valor = "Aqui va otro color"; 
cambiandoColor.StatusColor = "PaleGreen"; 
test.Add(cambiandoColor);