2010-11-06 34 views
1

我有一個XXXCustomControl.cs類和C#類裏面我想通過如何從CustomControl.cs C#文件訪問XAML資源?

groupStyle.ContainerStyle = this.FindResource("GroupHeaderStyle") as Style; 

的GroupHeaderStyle訪問,但這種風格被定義在其他地方(無論這是...)

現在我的問題:什麼是最好的地方把我的GroupHeaderStyle和如何獲得它通過

FindResource從C#代碼?

回答

2

你應該包括含有風格融入您的應用程序的資源字典作爲MergedDictionary您的XAML文件:

<Application.Resources> 
    <ResourceDictionary> 
     <!-- here you can add some more resources --> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="mystyles.xaml"/> 
      <!-- here you can add some dictionaries --> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

在這裏看到的例子:http://www.wpftutorial.net/MergedDictionaryPerformance.html

或者實際上你可以直接把你的風格定義爲應用程序的資源,沒有合併的資源字典。但是這樣,應用程序的資源通常會變得非常快。

編輯:
對於庫的情況,您沒有可用的App.xaml。所以,你需要做的基本上是以下幾點:

  1. 添加資源字典到您的項目,並定義所需的樣式出現。
  2. 在控件的資源中,將您的字典稱爲合併字典。

請注意,您需要指定的完整路徑(「pack URI」)的字典:

<Control.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Control.Resources> 
+0

是的,我這樣做我的程序項目,但我沒有想到控制項目需要/有一個app.xaml文件。似乎第三方免費的網絡自定義控制項目被作者ROFL翻錄:P似乎一個自定義控件庫只有一個Generic.xaml ...那麼我應該如何從我的c#代碼隱藏中訪問這個generic.xaml? – Elisabeth 2010-11-06 12:31:50

+0

@Lisa:你在開發一個圖書館,而不是一個應用程序? – Vlad 2010-11-06 12:33:31

+0

實際上是:-) 10 now ... LOL – Elisabeth 2010-11-06 12:35:16

5

如果你的風格是一個資源字典中的定義,你可以隨時在代碼

訪問它的背後
Uri resourceLocater = new Uri("/AssemblyName;component/DictionaryName.xaml", System.UriKind.Relative); 
ResourceDictionary resourceDictionary = (ResourceDictionary)Application.LoadComponent(resourceLocater); 
groupStyle.ContainerStyle = resourceDictionary["GroupHeaderStyle"] as Style;