WPF随手小记之二 ——改变DataGrid样式

大部分时候我们并不需要手动改变DataGrid的样式,因为用默认的其实也看得过去,而且在DataGrid中的数据也远比外观重要。

但总有时候,我们需要做点必要的UI修改来使DataGrid更美观。

一般大家都会想到改Background属性的值,但是改完你会发现,无论你怎么改,DataGrid的外观就是不变。。。。。

下面给出XAML代码,示范将UI改为黑底白字。

<DataGrid x:Name="StatisticsDataGrid" IsReadOnly="True" Margin="0,70,0,0" Height="310" VerticalAlignment="Top" Background="{DynamicResource ThemeBrushKey}">

                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="Background" Value="{DynamicResource ThemeBrushKey}"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Style>
                    
                </DataGrid.CellStyle>

                <DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <Setter Property="Background" Value="{DynamicResource ThemeBrushKey}"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Style>
                </DataGrid.RowStyle>
                
                <DataGrid.RowHeaderStyle>
                    <Style TargetType="DataGridRowHeader">
                        <Setter Property="Background" Value="{DynamicResource ThemeBrushKey}"/>
                        <Setter Property="Foreground" Value="White"/>
                    </Style>
                </DataGrid.RowHeaderStyle>
                
                <DataGrid.ColumnHeaderStyle>
                    <Style TargetType="DataGridColumnHeader">
                        <!--<Setter Property="Background" Value="{DynamicResource ThemeBrushKey}"/>
                        <Setter Property="Foreground" Value="White"/>-->
                        <Setter Property="Visibility" Value="Collapsed"/>
                    </Style>
                </DataGrid.ColumnHeaderStyle>
               
            </DataGrid>

其中,Background的值可以随意更改为自己喜欢的,示范里的是我自己的资源文件。

↓修改前的样式。

↓修改后

原文地址:https://www.cnblogs.com/provissy/p/4130558.html