2009-12-04 63 views

回答

36

您可以處理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

1

重要:一定要始終指定默認值不在行被一種條件或任何其他風格着色。

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

PS。我在Silverlight並沒有證實在WPF

這種行爲
10

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); 
相關問題