所有,我对WPF相对较新。我一直在寻找答案,但我发现的是如何在运行时对行进行着色而不是列;例如以下问题:
等。
我在MSDN DataGrid pages上看到了CellStyle
属性,但我对它的使用并不明显,尽管我也在搜索它。
如何在运行时更改整列的背景颜色?
感谢您的时间。
答案 0 :(得分:23)
我使用它的唯一方法是自己设置列(不使用AutoGenerate)。首先要做的是定义列:
<DataGrid x:Name="Frid" ItemsSource="{Binding Path=.}">
<DataGrid.Columns>
<DataGridTextColumn Header="First Name"
Binding="{Binding Path=FirstName}">
</DataGridTextColumn>
<DataGridTextColumn Header="Last Name"
Binding="{Binding Path=LastName}">
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
然后,您需要设置每个列CellStyle并将Background绑定到您可以在Window.Resources声明的静态资源:
<Window x:Class="WpfApplication1.MainWindow" ...>
<Window.Resources>
<SolidColorBrush x:Key="clBr" Color="White" />
</Window.Resources>
...
列:
<DataGridTextColumn Header="First Name"
Binding="{Binding Path=FirstName}">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background"
Value="{StaticResource clBr}" />
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
然后你可以通过代码或xaml操作来操作静态资源。
希望它有所帮助。
答案 1 :(得分:13)
有点旧,但以下是以编程方式执行此操作的方法(对于AutoGen列):
private void dgvMailingList_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
e.Column.CellStyle = new Style(typeof(DataGridCell));
e.Column.CellStyle.Setters.Add(new Setter(DataGridCell.BackgroundProperty, new SolidColorBrush(Colors.LightBlue)));
}
同样的方法也可以应用于非AutoGen列。