WPF 设置DataGrid 选中的背景色和前景色

<DataGrid >

            <DataGrid.CellStyle>
                <Style TargetType="DataGridCell">
                    <Style.Triggers>

                        <Trigger Property="IsSelected" Value="True">
                            <Setter Property="Background" Value="Red"/>
                            <Setter Property="Foreground" Value="Yellow"/>
                        </Trigger>

                    </Style.Triggers>

                </Style>

            </DataGrid.CellStyle>

        </DataGrid>

  

代码动态设置:

Style styleCells = new Style(typeof(System.Windows.Controls.DataGridCell));
            //styleCells.Setters.Add(new Setter
            //{
            //    Property = System.Windows.Documents.TextElement.ForegroundProperty,
            //    Value = new SolidColorBrush(System.Windows.Media.Colors.Black)
            //});

            Trigger triger = new  Trigger()
            {
                Property = DataGridCell.IsSelectedProperty,
                Value = true
            };
            triger.Setters.Add(new Setter()
            {
                Property = Control.BackgroundProperty,
                Value = new SolidColorBrush(System.Windows.Media.Colors.Red)
            });
            triger.Setters.Add(new Setter()
            {
                Property = Control.ForegroundProperty,
                Value = new SolidColorBrush(System.Windows.Media.Colors.White)  
            });

            styleCells.Triggers.Add(triger);


            this.dataGrid.CellStyle = styleCells;

  

代码设置datagrid 列头部(DataGridColumnHeader)的颜色:

Style chdStyle = new Style(typeof(System.Windows.Controls.Primitives.DataGridColumnHeader));
            chdStyle.Setters.Add(new Setter
            {
                Property = System.Windows.Documents.TextElement.ForegroundProperty,
                Value = new SolidColorBrush(System.Windows.Media.Colors.Black)
            });
            this.dataGrid.ColumnHeaderStyle = chdStyle;

  

或者修改ui:

     <DataGrid.ColumnHeaderStyle>
                <Style TargetType="DataGridColumnHeader">
                    <Style.Setters>
                        <Setter Property="Background" Value="Red"></Setter>
                        <Setter Property="Foreground"  Value="White"></Setter>
                    </Style.Setters>
                </Style>
              </DataGrid.ColumnHeaderStyle> 

  

fffffffffffffffff
test red font.
原文地址:https://www.cnblogs.com/wgscd/p/14759657.html