I’m currently getting to grips with WPF resources and wondering if you can help me:
I have a WPF window which contains its own resources. It also contains a content control which changes its content depending on what is selected in a tree view, e.g.:
contentControl1.Content = someUserControl;
This can be a UserControl e.g. SomeUserControl which uses a static resource which I have defined in the window xaml.
When creating an instance of SomeUserControl in the window code behind, I get an XMLParseException (‘Provide value on ‘System.Windows.StaticResourceExtension’ threw an exception.’). This is on the line containing the binding to the static resource.
To solve this, I added this to the constructor of SomeUserControl (parentResources being the window’s resources from where someUserControl is instantiated):
public SomeUserControl(ResourceDictionary parentResources)
{
this.Resources.MergedDictionaries.Add(parentResources);
InitializeComponent();
}
Is this the best approach for finding resources in this particular case? Thanks for any help.
I assume you have a
{StaticResource myResource}. Have you tried using{DynamicResource myResource}?See http://msdn.microsoft.com/en-us/library/ms748942.aspx
EDIT
Ok, given that you’re resource is a converter, which cannot use a dynamic resource, then I think what you’re doing is probably as a good a solution as any.
The underlying issue is that at the moment that your control is instantiated, it is not a part of the Window and so it doesn’t have any access to the Window’s resources. And as the term static in
StaticResourceimplies, the control expects that the resource is going to be available. So you have to make it available when the control is instantiated.You might also want to look at something like Prism and it’s Region’s which might be a better way to handle swapping out your “controls” (depending on your needs).