欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

wpf dataGrid 选中行 失去焦点时 的背景颜色的更改 4.0及4.5差异

程序员文章站 2022-03-07 17:05:07
...

在.net 4.5时直接使用如下方式修改即可

关于 wpf dataGrid 选中行 失去焦点时 的背景颜色的更改。很简单的方式,在datagrid的resource中更改InactiveSelectionHighlightBrushKey属性的值即可。

关键代码如下:

            <DataGrid.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Yellow"/>
            </DataGrid.Resources>

 

完整的简单代码如下:

        <DataGrid Name="grid1" HorizontalAlignment="Left" Height="120" Margin="75,86,0,0" VerticalAlignment="Top" Width="282">
            <DataGrid.Columns>
                <DataGridTextColumn Header="编号" Binding="{Binding compan.ID}"></DataGridTextColumn>
                <DataGridTextColumn Header="公司" Binding="{Binding CompanyName}"></DataGridTextColumn>
                <DataGridTextColumn Header="固定资产" Binding="{Binding FixedAssets}" Width ="*"></DataGridTextColumn>
            </DataGrid.Columns>
            <DataGrid.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Yellow"/>
            </DataGrid.Resources>
        </DataGrid>

在.net 4.0 时需使用如下方式修改,否则窗口在设计时无法预览

                <DataGrid.CellStyle>
                    <!--Override Highlighting so that its easy to see what is selected even when the control is not focused-->
                    <Style TargetType="{x:Type DataGridCell}">
                        <Style.Triggers>
                            <Trigger  Property="IsSelected" Value="true">
                                <Setter Property="Background" Value="#FF72DBE0" />
                                <Setter Property="BorderBrush" Value="#FF72DBE0" />
                            </Trigger>
                            <MultiDataTrigger>
                                <MultiDataTrigger.Conditions>
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsSelected}" Value="True" />
                                    <Condition Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=DataGrid}, Path=IsKeyboardFocusWithin}" Value="False" />
                                </MultiDataTrigger.Conditions>
                                <MultiDataTrigger.Setters>
                                    <Setter Property="Background" Value="#FF7ECB7E" />
                                    <Setter Property="BorderBrush" Value="#FF7ECB7E" />
                                </MultiDataTrigger.Setters>
                            </MultiDataTrigger>
                        </Style.Triggers>
                    </Style>
                </DataGrid.CellStyle>

 Setter 的赋值方式也可使用已指定的系统颜色

<Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}" />

 

相关标签: wpf