2011-04-01 71 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

相关问题