Is it possible to add wpf ResourceDictionary to the application from the xaml file UserControl?

Is it possible to add ResourceDictionary at application level from xaml UserControl.

i.e. do the same from UserControl xaml as in C #:

if (Application.Current == null) new Application(); Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() {...}); 
+4
source share
1 answer

You can write an ApplicationDictionaryMerger class that takes dictionaries as its contents and adds them to the applicationโ€™s MergedDictionaries , for example:

 [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; } } } 

The only thing you need to do is that you need to instantiate an object like the one above from XAML.

Initially, I thought that adding it to the Resources section of any control in your XAML would be fine, but then it turns out that the XAML loader does not create resources that are not used. So I came up with another workaround: setting the object as the value of any Tag control.

I would be very interested to know if there is a better way to ensure that ApplicationDictionaryMerger .

Here's how to use it:

 <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
source

Source: https://habr.com/ru/post/1346246/


All Articles