Is it possible to add wpf ResourceDictionary in the Application from a UserControl xaml file?
Is it possible to add a ResourceDictionary in the application level from a UserControl xaml.
i.e. do the same thing from UserControl xaml than the following in C#:
if (Application.Curr开发者_如何学Pythonent == null) new Application();
Application.Current.Resources.MergedDictionaries.Add(new ResourceDictionary() {...});
You can write an ApplicationDictionaryMerger
class that accepts dictionaries as its content and adds them to the MergedDictionaries
of the application, 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 catch then is that you need to instantiate an object like the 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 instantiate resources that are unused. So I came up with another workaround: setting the object as the value of any control's Tag
property.
I 'd be very interested to know if there's a better way of ensuring that the ApplicationDictionaryMerger
is instantiated.
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>
精彩评论