Multiple ResourceDictionary with same DataTemplate key? - wpf

I have a ResourceDictionary such as (MyResourceDictionary):
<ResourceDictionary xmlns
.....
>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="SeriesTwo.xaml" />
</ResourceDictionary.MergedDictionaries>
<DataTemplate x:Key="SeriesDetailedInformation">
<StackPanel>
......content...
</StackPanel>
</DataTemplate>
</ResourceDictionary>
SeriesTwo.xaml looks like this and also has the DataTemplate with the same name
<ResourceDictionary xmlns=
.....
>
<DataTemplate x:Key="SeriesDetailedInformation">
<DataGrid>
......content...
</DataGrid>
</DataTemplate>
</ResourceDictionary>
On my view page, which SeriesDetailedInformation data template gets used? Does it depend on which resource dictionary I reference first on my page?
Any good links and other reading material regarding this topic is also appreciated.

A couple of things from this page seem relevant to your question:
Lookup behavior within the MergedDictionaries collection searches the
last-added ResourceDictionary first, and the search stops as soon as a
requested key is found. In other words, the retrieval logic from the
collection of merged resource dictionaries is last in, first out.
And:
Resources in a merged dictionary occupy a location in the resource
lookup scope that is just after the scope of the main resource
dictionary they are merged into.
From this I gather that the DataTemplate defined in your main dictionary would be used first, then SeriesTwo, and any referenced before/above SeriesTwo after that.
Also, why not just try it out and see what happens? I maintain a solution I call "DumbCrapTestApp" where I test stuff like this when I'm curious about how something works. It has a console app for when I just need to test something within the language, and a WPF and a Silverlight app for when I want to try something there. If I needed a WinForms app, I'd just add one and do my thing there. I simply put whatever code I want to test into the relevant app, set it as my Startup Project, and away I go. It's really useful for figuring out these little things and I've even used it to get clarification and verify answers before I post them here on SO.

Related

Edit ResourceDictionary from an external assembly

I've been searching around if it is possible for an assembly to change the ResourceDictionary values from another assembly at runtime. So far I've found nothing.
Here´s the deal. I have a UserControl that will work independently so it can be fit into different projects. My UserControl has its own Resources.xaml (Compiled as Resources).
I have a second assembly that it used as a setup tool for this user control. It basically just reads the UserControl Resources.xaml (which is working great) and then replaces the values of the Resources.Xaml. Trouble is, I cannot change the resource values.
Here's the code I use on my setup tool to read the ResourceDictionary:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Control;component/Configuration/Resources.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
To change this values I've tried something like:
this.Resources.MergedDictionaries.First()["IsZoomable"] = false;
It does recognize the resources but it wont change it. Is it even possible to change the values of the dictionary of another assembly at runtime or will I need to create an external dictionary that can be acessed by both assemblies?
EDIT:
The user control contains the Resources.xaml. I've defined the Resources in this control like this:
<UserControl.Resources>
<ResourceDictionary Source="Configuration/Resources.xaml"/>
</UserControl.Resources>
The setup tool can acess this resources but I'm not able to change them. When I do, the user control still reads the old values. Resources are defined in the setup tool like so:
<Window.Resources>
<ResourceDictionary Source="pack://application:,,,/Control;component/Configuration/Resources.xaml"/>
</Window.Resources>
Yes, you can change the value of a resource at runtime.
Since you have merged the dictionary, you can change the value like this:
this.Resources["IsZoomable"]=false;
Make sure that the resource key matches the actual key.
If you have merged the dictionary in app.xaml, then you can use:
Application.current.Resources["IsZoomable"]=false;

Resources not resolving from ResourceDictionaries

I'm having problems resolving Resources from my ResourceDictionaries.
I decided to refactor my rather large ResourceDictionary into individual dictionary files, organized into subfolders.
I have a ResourceLibrary.xaml under Resources:
<ResourceDictionary x:Class="MyProject.Resources.ResourceLibrary"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<ResourceDictionary.MergedDictionaries>
<!-- Colours -->
<ResourceDictionary Source="Colors/ConnectedCellColor.xaml" />
<!-- Brushes -->
<ResourceDictionary Source="Brushes/ConnectorCellBrush.xaml" />
<!-- Control Templates -->
<ResourceDictionary Source="ControlTemplates/ConnectorCellTemplate.xaml" />
<!-- Base Styles -->
<ResourceDictionary Source="BaseStyles/ConnectorBaseStyle.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
The class is there for a reason, in the code behind, I can add [Export(typeof (ResourceDictionary))] so MEF can find it.
I have a View: (simplified)
<UserControl x:Class="MyProject.ConnectorCellView"
Style="{StaticResource ConnectorBaseStyle}"
</UserControl>
ConnectorBaseStyle:
<ResourceDictionary>
<Style x:Key="ConnectorBaseStyle" TargetType="UserControl">
<Setter Property="Template" Value="{StaticResource ConnectorCellTemplate}" />
</Style>
</ResourceDictionary>
The template has StaticResources to try and get a Brush and a colour.
All of these StaticResources will not resolve any more.
I thought it might have been an order issue, but since these resources are contained in a plugin to my main program, I use MEF and ImportMany to get all the exported ResourceDictionaries, and in my Caliburn.Micro bootstrapper:
public void OnImportsSatisfied()
{
foreach (ResourceDictionary resourceDictionary in ResourceDictionaries)
{
Application.Resources.MergedDictionaries.Add(resourceDictionary);
}
}
(Neat trick I found somewhere)
I can actually run my program, and when that view is created it throws an exception when trying to set the style:
System.InvalidCastException
Unable to cast object of type 'MS.Internal.NamedObject' to type System.Windows.FrameworkTemplate'.
The only information I've found relating to this has to do with the order resources are defined, but from the order I have them in ResourceLibrary, it should work.
When the exception is thrown, I can examine Application.Current.Resources.MergedDictionaries,
and see the resources.
I've tried various ways of specifying the Source in ResourceLibrary
<ResourceDictionary Source="/MyProject;component/Resources/BaseStyles/ConnectorBaseStyle.xaml" />
etc, no effect on finding them. These resources are only used by the plugin code.
The only thing that seemed to work was changing all the StaticResources to DynamicResources
which doesn't make sense to me, if it is an order issue, why would Static work when they're all in the same file?
Some of my styles used BasedOn, and they don't work with DynamicResource.
Can you help me understand why this is happening, and how to make it work?
It is an ordering problem but not with the ordering of your merging - it's with the order of loading. Here's basically what happens when the ResourceLibrary dictionary loads:
ConnectedCellColor instantiates
ConnectedCellColor loads into ResourceLibrary
ConnectorCellBrush instantiates
ConnectorCellBrush loads into ResourceLibrary
ConnectorCellTemplate instantiates
ConnectorCellTemplate loads into ResourceLibrary
ConnectorBaseStyle instantiates
ConnectorBaseStyle loads into ResourceLibrary
The problem here is that where before with your single file you had a single instantiation step, you now have that broken up into multiple steps, each of which happen independently. When ConnectorBaseStyle is instantiated ConnectorCellTemplate has been loaded but ResourceLibrary's contents aren't known to ConnectorBaseStyle at this point. With DynamicResource this isn't a problem because those references can just resolve at step 8, but StaticResource requires immediate resolution at step 7.
The simplest fix is to use Dynamic wherever you can. For places that require Static (like BasedOn) you need to guarantee that the resource will be available during instantiation, either by also merging, for example, ConnectorCellTemplate into ConnectorBaseStyle, or by merging everything that's needed into App.xaml which is available to everything. This can make things complicated and hard to manage as you get more files and do merging into multiple places but at least the resource system is smart enough to recognize duplicates so in the case above you would still only get a single instance of ConnectorCellTemplate even though it is being merged at two places.

Referencing xaml dictionary resources from pages in a class library

I'm having a little problem with Merging dictionaries in my WP7 application, The app contains a lot of pages and the loading time exceeded the market place limit which is 5 seconds, I had to put the majority of the pages and UI stuff in a separate class library to cut off the loading time, the problem is that the pages ware referencing static resources in the global app.xaml, I tried to move the xaml stuff in App.xaml to a separate resource dictionary in the class library project. I also referenced that resource dictionary file in every page.
<phone:PhoneApplicationPage.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Resources.xaml" />
</ResourceDictionary.MergedDictionaries>
<Converters:TimeSpanToWeekAndDayConverter x:Key="weekAndDayConverter"/>
</ResourceDictionary>
</phone:PhoneApplicationPage.Resources>
The problem is that I always receive this exception :
Failed to assign to property 'System.Windows.ResourceDictionary.Source'.
I also tried to change the build action of that resource dictionary from Page to Resource to Content (With all their specific path syntax considerations) without any luck.
I hope someone has a idea.
Thanks
I don't think you need to move the resources - you can keep them in the App resources. It should work.
You need to reference the dictionary by using the full name. In this case:
Source="/AssemblyName;component/Resources.xaml"
Otherwise, it won't know how to find it.

How can i make a prefix so i can address a folder in xaml

I always have problems making new prefixes in xaml. Most of the time, i get the message that the URI cannot be found in the assembly. My setup:
I have a WPF project (in a solution with class libs and asp.NET projects) with a MainWindow.xaml file. The XAML starts with : Window x:Class="MainWindow" ... .
So as default, there's no namespace given to it. In that same project i made a folder "Folder". In that folder, i have resx-files. What i need to do is make a prefix in xaml so i can address those files. I was thinking of :
xmlns:p="clr-namespace:WpfApplication.Folder"
and then for my controls
<Label Content="{x:Static p:NameResxFile.KeyName></Label>
However, the prefix generates the "URI cannot be found in the assembly" error. I'm i just failing at making prefixes?
Thanks in advance.
EDIT
If you cannot make a namespace ref to a folder, what is happening here?
xmlns specifies namespaces, it does not bother with folders or files, if you need access to an external resource you can load it into your control's resources via ResourceDictionary.
There was something like this i think:
<Window.Resources>
<ResourceDictionary x:Key="ExternalRes" Source="Folder/File.xaml"/>
....
</Window.Resources>
To reference an element of resource dictionary you should add that dictionary to your control's Resources collection or register it in the App.xaml file. After that you could just use StaticResource extension to get access to the element. Your code will look like this:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/Folder/NameResxFile.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<!-- ... -->
<Label Content="{StaticResource KeyName}"/>
Things get trickier if you want to put the resource dictionary to another assembly and reference it. For this purpose refer to PackURIs in WPF article.

Static resource shared in merged dictionaries

I'm currently working on having dictionaries of styles and templates that I can dynamically apply to my application. Before this "new wanted" dynamical behavior, I had several resource dictionaries, one for each styled control, that I merged in the App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ColorsDictionary.xaml"/>
<ResourceDictionary Source="ControlsTemplatesDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now, I'd like my application to be styled, so I decided to merge all my previous resources into a new one called "MyFirstTemplates" and to add only this dictionary to the App.xaml.
New dictionary "MyFirstTemplates.xaml":
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">"
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ColorsDictionary.xaml"/>
<ResourceDictionary Source="ControlsTemplatesDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
New App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="MyFirstTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="{x:Type Window}"/>
</ResourceDictionary>
</Application.Resources>
Note: The default style for the Window is to correct a bug of WPF 4, see Adding a Merged Dictionary to a Merged Dictionary
Now that I have made this change, I cannot use a color resource from "ColorsDictionary.xaml" as a StaticResource in "ControlsTemplateDictionary.xaml" anymore. If I change back to merging these files in the app.xaml, everything works. To make it work, I have to change these StaticResource for DynamicResource. Do you have any idea why this doesn't work anymore?
Thank you :-)
By moving the dictionaries out of App.xaml the resources from each dictionary aren't in the other's resource tree during loading of MyFirstTemplates.xaml. Your original setup first loaded ColorsDictionary which was then available through App resources to ControlsTemplatesDictionary while it loaded. In your new setup, in order for the color resource to be available in App resources it needs to be loaded through MyFirstTemplates, which in turn requires loading of both dictionaries, which in turn requires access to the color resource... so it's sort of an infinite loop of references that can't be resolved statically. DynamicResource can wait until everything is loaded and then access the color without issue.
To fix either use Dynamic or merge ColorsDictionary directly into ControlsTemplatesDictionary.
Great answer by John explaining why this is happening.
So the problem is that when using merged dictionaries within a merged dictionary, the inner dictionaries can't "use" each other as StaticResource.
Basic solutions:
Use DynamicResource
Use just a single level of hierarchy from App.xaml when using StaticResource
Both of these solutions have problems. DynamicResource has a performance problem. The 2nd solution limits you on how you organize your XAML resources.
Alternative solution:
I created a small simple program (provided below in GitHub) that will run as a pre-build event and merge XAML files from a folder into one long .XAML file. Well, they need to be with a different extension (.txaml), otherwise they will be compiled.
This allows to structure resources folders and files however you want, without WPF’s limitations. StaticResource and the designer will work always.
The code in GitHub contains a simple solution that contains the merging program. It merges 2 folders into 2 files. One for App.xaml resources and the other for Generic.xaml resources. The .xaml files in a "Controls" project (There's also "Main" project).
Blog post explaining this

Resources