2011-06-30 41 views
2

我在我的項目中有一個文件夾,模板,完整的(已編譯的)XAML ResourceDictionaries。動態加載ResourceDictionary

在UserControl中,我想要將所有模板加載到ResourceDictionary中。我會使用如下代碼:

public MyView() 
{ 
    InitializeComponent(); 
    foreach (var resourceUri in new GetResourceUrisFromTemplatesFolder()) 
     Resources.MergedDictionaries.Add(
      new ResourceDictionary 
       { Source = new Uri(resourceUri, UriKind.Relative) }); 
} 

我需要寫的是GetResourceUrisFromTemplatesFolder方法。我需要它來發現該文件夾中的所有資源。

中的URI可以採用這樣的形式像/MyAssembly;component/MyNS/Templates/Template12345.xaml../../Templates/Template12345.xaml

這可能嗎?

我是否必須手動轉換程序集編譯資源中的名稱(MyAssembly.g.resources)?

回答

1

我必須手動轉換程序集編譯資源中的名稱(MyAssembly.g.resources)嗎?

這可能是這種情況,我自己會接近這樣的說法,但關於如何做到這一點has been answered已經所以它應該是沒有太大問題的問題。確保字典的編譯動作相匹配,並且您可能希望用包uri作爲名稱的前綴。

+0

是的,它原來是很容易 –

5

BTW,還可以手動加載一個ResourceDictionary的,因爲它似乎:

ResourceDictionary dict = new ResourceDictionary(); 
System.Windows.Application.LoadComponent(dict, 
    new System.Uri("/SomeAssembly;component/SomeResourceDictionary.xaml", 
    System.UriKind.Relative)); 

之後,可以使用上它具有鍵的屬性的foreach跟那個字典對象

http://msdn.microsoft.com/en-us/library/ms596995(v=vs.95).aspx說等

加載的XAML文件可以是應用程序定義文件(例如App.xaml)>或頁面文件(例如MainPage.xaml)。 XAML文件可位於以下位置之一:

  • 包含在應用程序包中。
  • 嵌入在應用程序程序集中。
  • 嵌入在原始站點的庫組件中。
+0

似乎並不加載了'Source'字典不同。 「複雜」部分不是加載字典,而是生成Uris。 –