使用 ThemeResources 更改 stackpanel.background

Changing stackpanel.background using ThemeResources

所以,我有这个本地画笔资源,我将用于我的一些堆栈面板,我想知道如何在 c# 中访问它 class。我将创建堆栈面板,我需要在 c#

中将背景设置为堆栈面板

在 XAML 中,可以通过以下方式轻松设置控件背景:

Background="{ThemeResource SubPanelBackground}"

但我无法找到一种在 C# 中执行此操作的方法,因为我将按需创建一些控件。这是一个代码片段

StackPanel Group2Panel = new StackPanel();
Group2Panel.Orientation = Orientation.Horizontal;
Group2Panel.Height = 80;
Group2Panel.Margin = new Thickness(10);
Group2Panel.Background = /*Now i cant find what to enter here*/;

谁能找到我应该输入的主题资源画笔?

确保您可以从您的代码访问资源字典:

Brush panelBrush = Resources["SubPanelBackground"] as Brush;
Group2Panel.Background = panelBrush

例如,如果资源字典保存在与 .cs 相同的 class 中,例如 page1.xaml 和 page1.xaml.cs,您应该使用此

Brush panelBrush = Resources["SubPanelBackground"] as Brush;
Group2Panel.Background = panelBrush;

或者

Group2Panel.Background = Resources["SubPanelBackground"] as Brush;

但是如果资源字典保存在 app.xaml 中(因此它可以在应用程序的任何地方使用)你应该使用它。

Brush panelBrush = Application.Current.Resources["SubPanelBackground"] as Brush;
Group2Panel.Background = panelBrush;

Group2Panel.Background = Application.Current.Resources["SubPanelBackground"] as Brush;

唯一不同的是这个使用的是Application.Current.Resources