且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

非活动时 DataGrid 的选定行颜色

更新时间:2023-12-05 10:27:40

自己找答案.

将画笔添加到 DataGrid 的资源中,它可以从后面的代码中更改其颜色"属性,并将 HighlightBrushKey 引用给它:

Add to DataGrid's resources the brush, which can change its 'Color' property from code behind, and reference HighlightBrushKey to it:

<DataGrid.Resources>
    <SolidColorBrush x:Key="SelectionColorKey" Color="DarkGray"/>
    <Style TargetType="DataGridRow">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Source={StaticResource SelectionColorKey}, Path=Color}"/>
        </Style.Resources>
    </Style>
</DataGrid.Resources>

然后添加 DataGrids 事件处理程序以手动更改颜色:

Then add DataGrids event handlers to manually change the color:

private void DataGrid1_LostFocus(object sender, RoutedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = Colors.DarkGray;
}

private void DataGrid1_GotFocus(object sender, RoutedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = SystemColors.HighlightColor;
}

private void DataGrid1_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
    ((SolidColorBrush)DataGrid1.Resources["SelectionColorKey"]).Color = Colors.DarkGray;
}