C# 可以在代码隐藏中设置DataGrid.Resources吗?

C# 可以在代码隐藏中设置DataGrid.Resources吗?,c#,wpf,xaml,datagrid,code-behind,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

我想在代码隐藏中更改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>

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

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

丹尼尔·萨托里:

非常感谢你。你的答案是我问题的解决方案,但也有例外。此代码解决的问题:

var converter = new BrushConverter();
var background = FindResource(SystemColors.HighlightBrushKey);
var foreground = FindResource(SystemColors.HighlightTextBrushKey);

this.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, (Brush)converter.ConvertFromString(background.ToString()));
this.Resources.Add(SystemColors.InactiveSelectionHighlightTextBrushKey, (Brush)converter.ConvertFromString(foreground.ToString()));

谢谢,但您的代码给了我未处理的异常:System.InvalidCastException:System.Windows.Media.Color类型的对象无法重新键入System.Windows.Media.Brush.Solutioned by:var converter=new BrushConverter();var background=FindResource(SystemColors.HighlightBrushKey);var前台=FindResource(SystemColor.HighlightTextBrushKey);this.Resources.Add(SystemColors.inactiveselection highlightbrushkey,(Brush)converter.ConvertFromString(background.ToString());this.Resources.Add(SystemColors.inactiveselection highlighttextbrushkey,(Brush)converter.ConvertFromString(foreground.ToString())@Bugscz为这个错误感到抱歉。我会更正答案的。然而,这种方法有效吗?
var converter = new BrushConverter();
var background = FindResource(SystemColors.HighlightBrushKey);
var foreground = FindResource(SystemColors.HighlightTextBrushKey);

this.Resources.Add(SystemColors.InactiveSelectionHighlightBrushKey, (Brush)converter.ConvertFromString(background.ToString()));
this.Resources.Add(SystemColors.InactiveSelectionHighlightTextBrushKey, (Brush)converter.ConvertFromString(foreground.ToString()));