2009-12-04 16 views

risposta

36

È possibile gestire l'evento LoadingRow di DataGrid per rilevare quando viene aggiunta una riga. Nel gestore eventi è possibile ottenere un riferimento al DataRow che è stato aggiunto al DataTable che funge da ItemsSource. Quindi puoi aggiornare il colore di DataGridRow come preferisci.

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); 
    }   
} 

a firmare per l'evento in XAML:

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

O in C#:

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

assicurarsi di assegnare valori predefiniti per le righe il cui colore non è attivato da una condizione –

+0

grazie. è stato un modo semplice e sorprendente per me. – Nasenbaer

+0

Non funziona. l'oggetto è sempre nullo – Yusha

1

IMPORTANTE: essere sicuri di assegnare sempre di default per le righe che non sono essere colorati da una condizione o da qualsiasi altro stile.

Vedere la risposta a C# Silverlight Datagrid - Row Color Change.

PS. Sono in Silverlight e non hanno confermato questo comportamento in WPF

10

U può provare questo

Nel XAML

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

Nel datagrid

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

Nel codice ho una lezione con

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

Quando impostare il DataContext

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

Se non u impostare il colore della riga del valore di default è Grey

u può provare questo esempio con questo esempio

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); 
Problemi correlati