WPFデータグリッドを使用するときに列ヘッダーの背景色を変更するにはどうすればよいですか? xamlを直接変更する必要がありますか?
DataGridColumnHeaderをターゲットとするセッターでスタイルを使用します。
<DataGrid>
<DataGrid.Resources>
<Style BasedOn="{StaticResource {x:Type DataGridColumnHeader}}" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Background" Value="Blue" />
</Style>
</DataGrid.Resources>
</DataGrid>
これを使って:
<windows.Resources>
<LinearGradientBrush x:Key="HeaderBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FF6B8E95" Offset="0"/>
<GradientStop Color="#FF14A7C1" Offset="1"/>
<GradientStop Color="#FF1E424E" Offset="0.509"/>
<GradientStop Color="#FF1D4855" Offset="0.542"/>
<GradientStop Color="#FF1D4855" Offset="0.542"/>
<GradientStop Color="#FF193A44" Offset="0.526"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="HeaderBorderBrush" StartPoint="0.5,0" EndPoint="0.5,1">
<GradientStop Color="#FF1D1D1D" Offset="0.614"/>
<GradientStop Color="#FF007F96" Offset="0.853"/>
<GradientStop Color="#FF0AEAFA" Offset="1"/>
</LinearGradientBrush>
<Style x:Key="HeaderStyle" TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="{StaticResource HeaderBrush}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="BorderBrush" Value="{StaticResource HeaderBorderBrush}" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="MinWidth" Value="0" />
<Setter Property="MinHeight" Value="30" />
<Setter Property="Cursor" Value="Hand" />
</Style>
</Windows.Resources>
<Grid>
<DataGrid Name="dataGrid1" ColumnHeaderStyle="{StaticResource HeaderStyle}"/>
</Grid>
これが結果です:
var style = new Style(typeof(System.Windows.Controls.Primitives
.DataGridColumnHeader));
style.Setters.Add(new Setter(ToolTipService.ToolTipProperty
,"Your tool tip here"));
style.Setters.Add(new Setter { Property = BackgroundProperty, Value
= Brushes.Yellow });
dgExcelSheet.Columns[1].HeaderStyle = style;
<DataGridTextColumn Header="ID">
<DataGridTextColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Background" Value="Green"/>
</Style>
</DataGridTextColumn.HeaderStyle>
</DataGridTextColumn>