Мне нужно назначить цвет строке, которую я добавляю во время выполнения в DataTable. Как это может быть сделано?
Программное присвоение цвета строке в DataGrid
Ответы (3)
Вы можете обработать событие LoadingRow DataGrid, чтобы определить, когда добавляется строка. В обработчике событий вы можете получить ссылку на DataRow, который был добавлен в DataTable, который действует как ваш ItemsSource. Затем вы можете обновить цвет 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">
Or in C#:
this.dataGrid.LoadingRow += new EventHandler<Microsoft.Windows.Controls.DataGridRowEventArgs>(dataGrid_LoadingRow);
Вы можете попробовать это
В XAML
<Window.Resources>
<Style TargetType="{x:Type DataGridRow}">
<Style.Setters>
<Setter Property="Background" Value="{Binding Path=StatusColor}"></Setter>
</Style.Setters>
</Style>
</Window.Resources>
В сетке данных
<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);
ВАЖНО: всегда задавайте значения по умолчанию для строк, которые не окрашиваются условием или каким-либо другим стилем.
См. Мой ответ на C # Silverlight Datagrid - изменение цвета строк.
PS. Я использую Silverlight и не подтверждал такое поведение в WPF