所有,我对 WPF 比较陌生。我已经四处寻找答案,但我发现的只是如何在运行时对行而不是列进行着色;例如以下问题:
等。
我已经在MSDN DataGrid 页面CellStyle
上看到了该属性,但它的使用对我来说一点也不明显,尽管围绕它进行了搜索。
如何在运行时更改整个列的背景颜色?
谢谢你的时间。
所有,我对 WPF 比较陌生。我已经四处寻找答案,但我发现的只是如何在运行时对行而不是列进行着色;例如以下问题:
等。
我已经在MSDN DataGrid 页面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 列。