2015-11-02 51 views
-1

所以,我有這個本地刷資源,我將用於我的一些stackpanels,我想知道如何在c#類中訪問它。我將創建stackpanels,我需要設置背景的StackPanel的在C#使用ThemeResources更改stackpanel.background

在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刷嗎?

回答

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

1

確保您可以訪問資源字典從您的代碼:

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

有沒有辦法做到這一切在一行 還因爲我將使用一對夫婦不同的主題資源可以聲明多個themeResources – Albert

+1

@GurfX Group2Panel.Background = Resources [「SubPanelBackground」]作爲刷子< - 這是你的意思嗎? – tgpdyk

+0

是的,這就是我的意思,我認爲代碼都可以工作,但是這個錯誤發生。 '在mscorlib.ni.dll中發生類型'System.Runtime.InteropServices.COMException'的異常,但未在用戶代碼中處理 WinRT信息:找不到具有給定鍵的資源。 附加信息:未指定的錯誤' – Albert