[英]Change the Background Color of Entire Column of WPF DataGrid at RunTime
總而言之,我對WPF相對較新。 我一直在尋找答案,但我發現的是如何在運行時對行進行着色而不是列; 例如以下問題:
等。
我已經在MSDN DataGrid頁面上看到了CellStyle
屬性,但它的使用對我來說並不明顯,盡管也在搜索它。
如何在運行時更改整列的背景顏色?
謝謝你的時間。
我讓它工作的唯一方法是自己設置列(不使用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操作來操縱靜態資源。
希望能幫助到你。
有點舊,但以下是以編程方式執行此操作的方法(對於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列。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.