使用ThemeResources更改stackpanel.background

时间:2015-11-02 00:35:37

标签: c# xaml uwp

所以,我有一个本地刷资源,我将用于我的一些stackpanels,我想知道如何在c#类中访问它。我将创建stackpanels,我需要在c#

中将背景设置为stackpanel

在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*/;

任何人都可以找到我应该输入的找到themeresource画笔的东西吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

例如,如果资源字典与.cs保持在同一个类中,例如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