Merging Resources Dictionaries
i'm trying merging wpf resource dictionaries on the code behind but for some reasion this isn't working. If i try merge the dictionaries on the document itself it's running for instance:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication212;assembly=WpfApplication212">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Theme.xaml"></ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type local:URComboBox}" BasedOn="{StaticResource ComboBoxStyle}">
</Style>
This is working, but if i comment the ResourceDictionary.MergedDictionaries and in code try this:
ResourceDictionary skin = new ResourceDictionary();
skin.Source =开发者_JAVA技巧 styleLocation;
ResourceDictionary skinFather = new ResourceDictionary();
skinFather.MergedDictionaries.Add(skin);
skinFather.Source = styleLocationFather;
This will break because can't find the resource.
You can't use the Source property to load a Resource Dictionary from code.
From MSDN:
"Merged dictionaries can be added to a Resources dictionary through code. The default, initially empty ResourceDictionary that exists for any Resources property also has a default, initially empty MergedDictionaries collection property. To add a merged dictionary through code, you obtain a reference to the desired primary ResourceDictionary, get its MergedDictionaries property value, and call Add on the generic Collection that is contained in MergedDictionaries. The object you add must be a new ResourceDictionary. In code, you do not set the Source property. Instead, you must obtain a ResourceDictionary object by either creating one or loading one. One way to load an existing ResourceDictionary to call XamlReader.Load on an existing XAML file stream that has a ResourceDictionary root, then casting the XamlReader.Load return value to ResourceDictionary."
Hence, some pseudo code:
ResourceDictionary myResourceDictionary = XamlReader.Load(someXamlStreamReader);
anotherResourceDictionary.MergedDictionaries.Add(myResourceDictionary);
Here is another example of how to do it:
Uri uri = new Uri("/PageResourceFile.xaml", UriKind.Relative);
StreamResourceInfo info = Application.GetResourceStream(uri);
System.Windows.Markup.XamlReader reader = new System.Windows.Markup.XamlReader();
Page page = (Page)reader.LoadAsync(info.Stream);
精彩评论