WPF 改变Datagrid的选中行的颜色

C#

浏览数:912

2019-10-11

主要通过设置DataGrid的RowStyle和CellStyle即可。

             <Style TargetType="DataGridRow" x:Key="gridRowStyle">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="true">
                        <Setter Property="Background" Value="LightGray"/>
                    </Trigger>
                </Style.Triggers>
            </Style>

            <Style TargetType="DataGridCell" x:Key="gridCellStyle">
                <!--文字居中-->
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type DataGridCell}">
                            <Grid Background="{TemplateBinding Background}">
                                <ContentPresenter HorizontalAlignment="Center" />
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <!--被选中时,背景色改变-->
                <Style.Triggers>
                    <Trigger Property="DataGridCell.IsSelected" Value="True">
                        <Setter Property="Background" Value="Gray" />
                    </Trigger>
                </Style.Triggers>
            </Style>
       <DataGrid ScrollViewer.CanContentScroll="False" AutoGenerateColumns="False" CanUserAddRows="False"
             CellStyle="{StaticResource gridCellStyle}"
                      RowStyle="{StaticResource gridRowStyle}" />

 

作者:hbatjzyb