数据表格在未激活状态下的选中行颜色

81

当WPF DataGrid失去焦点时,我该如何样式化它以更改选择行的颜色?

12个回答

0

我曾经遇到过类似的问题。 情况是在DataGrid中为RowBackground和AlternatingRowBackground分配了颜色。 当DataGrid失去焦点时,选定的行变成灰色,当通过单击任何行使DataGrid重新获得焦点时,它会返回到正确的颜色。 这种效果很不好。 我从Steve Streeting在这里提出的解决方案开始:

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

但是通过更改Color =“Transparent”。

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

这个简单而令人满意地解决了问题。 适用于.net 4.5,不适用于.net 4.0

希望这个解决方案对您有用。

错误的行为:

incorrect behavior

正确的行为:

correct behavior


0

对于.NET 4.0或更高版本:也可以通过编程方式设置颜色:

if (TestDataGrid.RowStyle == null)
{
  TestDataGrid.RowStyle = new Style(typeof(DataGridRow));
}

// Set colors for the selected rows if focus is inactive
TestDataGrid.RowStyle.Resources.Add(SystemColors.ControlBrushKey, new SolidColorBrush(Colors.SkyBlue));
TestDataGrid.RowStyle.Resources.Add(SystemColors.ControlTextBrushKey, new SolidColorBrush(Colors.Black));

// Set colors for the selected rows if focus is active
TestDataGrid.RowStyle.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Red));
TestDataGrid.RowStyle.Resources.Add(SystemColors.HighlightTextBrushKey, new SolidColorBrush(Colors.White));

对于.NET 4.5或更高版本,可以通过以下方式以编程方式设置颜色:

if (TestDataGrid.Resources == null)
{
  TestDataGrid.Resources = new ResourceDictionary();
}

// Set colors for the selected rows if focus is inactive
TestDataGrid.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, new SolidColorBrush(Colors.SkyBlue));
TestDataGrid.Resources.Add(SystemColors.InactiveSelectionHighlightTextBrushKey, new SolidColorBrush(Colors.Black));

// Set colors for the selected rows if focus is active
TestDataGrid.Resources.Add(SystemColors.HighlightBrushKey, new SolidColorBrush(Colors.Red));
TestDataGrid.Resources.Add(SystemColors.HighlightTextBrushKey, new SolidColorBrush(Colors.White));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接