c# - DataGrid.Resources 可以在代码后面设置吗?

标签 c# wpf xaml datagrid code-behind

我想在后面的代码中更改 WPF DataGrid 的画笔颜色。 这是有效的 XAML 代码:

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

是否可以在代码隐藏中设置此 XAML 代码(在从默认 DataGrid 继承的自定义类的构造函数中)?

最佳答案

你可以这样做(如果你使用的是自定义类):

  public class CustomDataGrid : DataGrid
  {
    public CustomDataGrid()
    {
      var converter = new BrushConverter(); 
      var background = FindResource(SystemColors.HighlightBrushKey); 
      var foreground = FindResource(SystemColors.HighlightTextBrushKey);
      this.Resources.Add(SystemColors.InactiveSelectionHighlightBr‌​ushKey, (Brush)converter.ConvertFromString(background.ToString())); 
      this.Resources.Add(SystemColors.InactiveSelectionHighlightTe‌​xtBrushKey, (Brush)converter.ConvertFromString(foreground.ToString())); 
    }
  }

关于c# - DataGrid.Resources 可以在代码后面设置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48417400/

相关文章:

c# - 无法订阅使用 dday.ical 创建的 webcal 提要

c# - 使 ASP.Net 页面过期

c# - 按钮内的图像和标签在单击事件 wpf 上更新

.net - 更改wpf中的按钮边框厚度?

c# - 有没有一种好方法将 xaml 绑定(bind)到依赖于多个其他属性的属性?

c# - 为什么 minValue 是包含的,而 maxValue 是 Random.Next() 独占的?

WPF 数据网格标题文本绑定(bind)

所选行的WPF DataGrid RowStyle不改变背景和前景色

c# - WPF MVVM 绑定(bind)超链接 RequestNavigate 到 View 模型

xaml - XAML (WPF) 中的依赖注入(inject)