2011-04-01 74 views

回答

1

你可以寫一個ApplicationDictionaryMerger類接受字典作爲其內容,並將它們添加到應用程序的MergedDictionaries,例如:

[ContentProperty("Dictionaries")] 
public class ApplicationDictionaryMerger 
{ 
    private readonly ObservableCollection<ResourceDictionary> dictionaries = 
     new ObservableCollection<ResourceDictionary>(); 

    public ApplicationDictionaryMerger() 
    { 
     this.dictionaries.CollectionChanged += this.DictionariesChanged; 
    } 

    private void DictionariesChanged(object sender, 
            NotifyCollectionChangedEventArgs e) 
    { 
     // Do whatever you deem appropriate here to get the MergedDictionaries 
     var applicationDictionaries = 
      Application.Current.Resources.MergedDictionaries; 

     // Enhance this switch statement if you require more functionality 
     switch (e.Action) 
     { 
      case NotifyCollectionChangedAction.Add: 
       foreach (var dict in e.NewItems) 
       { 
        applicationDictionaries.Add((ResourceDictionary)dict); 
       } 
       break; 
     } 
    } 

    public IList Dictionaries 
    { 
     get { return this.dictionaries; } 
    } 
} 

唯一可以接受的是,您需要從XAML實例化上述對象。

最初我以爲將它添加到你的XAML中的任何控件的Resources部分都可以,但事實證明,XAML加載器不會實例化未使用的資源。所以我想出了另一個解決方法:將對象設置爲任何控件的Tag屬性的值。

我很想知道是否有更好的方法來確保ApplicationDictionaryMerger被實例化。

下面是如何使用它:

<Grid> <!-- can also be any other control --> 
    <Grid.Tag> 
     <sandbox:ApplicationDictionaryMerger> 
      <ResourceDictionary> 
       <!-- add all resources you need here --> 
      </ResourceDictionary> 
      <!-- you can also add more dictionaries here --> 
     </sandbox:ApplicationDictionaryMerger> 
    </Grid.Tag> 
</Grid> 
+1

的「ContentProperty」被稱爲「MergedDictionaries」,但在C#類的屬性是「字典」,並在XAML中,它的「資源字典」 ......療法絕是否有一些錯別字? – sthiers 2011-04-04 13:58:49

+0

@sthiers:「MergedDictionaries」應該是「字典」作爲屬性 - 感謝那裏的捕獲。在XAML中,您只需使用想要放入'Dictionaries'集合的類的名稱,就不會有錯字。 – Jon 2011-04-04 14:03:13

相關問題