【发布时间】:2013-03-16 15:55:43
【问题描述】:
所有,我对 WPF 比较陌生。我已经四处寻找答案,但我发现的只是如何在运行时对行而不是列进行着色;例如以下问题:
等。
我在MSDN DataGrid pages 上看到了CellStyle 属性,但它的用途对我来说一点也不明显,尽管也围绕它进行了搜索。
如何在运行时改变整列的背景颜色?
感谢您的宝贵时间。
【问题讨论】:
所有,我对 WPF 比较陌生。我已经四处寻找答案,但我发现的只是如何在运行时对行而不是列进行着色;例如以下问题:
等。
我在MSDN DataGrid pages 上看到了CellStyle 属性,但它的用途对我来说一点也不明显,尽管也围绕它进行了搜索。
如何在运行时改变整列的背景颜色?
感谢您的宝贵时间。
【问题讨论】:
我让它工作的唯一方法是自己设置列(不使用自动生成)。所以首先要做的是定义列:
<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 操作来操作静态资源。
希望对你有帮助。
【讨论】:
有点旧,但您可以通过以下方式以编程方式执行此操作(对于 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 列。
【讨论】: