DataGrid's selected row color when inactive

前端 未结 11 1343
轻奢々
轻奢々 2020-12-04 23:31

How can I style WPF DataGrid to change the color of selected row when DataGrid lost its focus?

11条回答
  •  清歌不尽
    2020-12-05 00:10

    For .NET 4.0 or higher: It is also possible to set the colors programmatically:

    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));
    

    For .NET 4.5 or higher there is the following alternative to set the colors programmatically:

    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));
    

提交回复
热议问题