我需要为我在运行时添加到 DataTable 的行分配颜色。如何才能做到这一点?
问问题
54620 次
3 回答
39
您可以处理 DataGrid 的 LoadingRow 事件以检测何时添加行。在事件处理程序中,您可以获得对添加到充当 ItemsSource 的 DataTable 的 DataRow 的引用。然后你可以随心所欲地更新 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);
于 2009-12-05T01:14:17.383 回答
10
你可以试试这个
在 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);
于 2011-04-28T04:51:28.370 回答
1
重要提示:请务必始终为未按条件或任何其他样式着色的行分配默认值。
请参阅我对C# Silverlight Datagrid - Row Color Change的回答。
PS。我在 Silverlight 中,但尚未在 WPF 中确认此行为
于 2010-01-17T02:52:35.687 回答