我需要在运行时向DataTable添加一行并为其分配颜色。这该怎么做?
您可以处理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);
试一下这个
在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 - Row Color Change。
附注:我在Silverlight中,尚未确认此行为在WPF中是否存在。