2009-12-04 18 views

Odpowiedz

36

Można obsłużyć zdarzenia LoadingRow DataGrid w celu wykrycia, kiedy dodawany jest wiersz. W module obsługi zdarzeń można uzyskać odwołanie do DataRow, które zostało dodane do DataTable, które działa jako Twoj ItemsSource. Następnie możesz zaktualizować kolor DataGridRow, jak chcesz.

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

Aby zapisać się na razie w XAML:

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

Lub w języku C#:

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

upewnij się, aby przypisać domyślne dla wierszy, których kolor nie jest wyzwalany przez warunek –

+0

dzięki. to była dla mnie niesamowita prosta droga. – Nasenbaer

+0

Nie działa. pozycja jest zawsze pusta – Yusha

1

WAŻNE: należy zawsze przypisywać domyślne dla wierszy, które nie są kolorowany przez warunek - lub jakikolwiek inny styl.

Zobacz moją odpowiedź na C# Silverlight Datagrid - Row Color Change.

PS. Jestem w Silverlight i nie potwierdziły to zachowanie w WPF

10

U może spróbować tej

W XAML

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

W datagrid

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

W kodzie mam klasa z

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

Po ustawieniu DataContext

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

Jesli nie ustawić kolor wierszu wartość domyślna jest szary

u mogą spróbować tej próbki z tej próbki

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); 
Powiązane problemy