views:

1276

answers:

2

How can I avoid Visual Studio designer errors when a WPF resource is defined in separate project?

I have three projects in a composite WPF application: the main application, an "infrastructure" library, and a "module" library. The main application references the other projects via their output DLLs (the projects are not located in a single solution together).

I am defining a skin (some brushes and styles in a ResourceDictionary) in the "infrastructure" library. I would like the main application to select a skin and make it available to the entire application (via MergedDictionaries in App.xaml).

In my module I want to use the resources defined in the skin that the main application loads. If I reference the resource as if it were locally available like this:

Background={StaticResource MainBackgroundBrush}

almost everything works as desired. The exception is that Visual Studio's designer gets confused and tells me that "StaticResource reference 'MainBackgroundBrush' was not found". This effectively prevents me from using the designer.

What can I do to define a "skin" ResourceDictionary in a project, reference that skin in the main application, and then use its resources in a module project?

+1  A: 

One possible solution is to use DynamicResource rather than StaticResource. The Visual Studio 2008 designer simply displays the controls without any styling, like VS2010 beta 1 does when it cannot resolve a StaticResource.

Using DynamicResource is appropriate in situations where a particular style may change at runtime, like when skinning.

I found some related questions supporting this:

I also found someone who states that DynamicResource should be used whenever a resource is not local:

emddudley
+1  A: 

You could create your own ResourceDictionary class, inheriting from ResourceDictionary. Then you can arrange that at design-time this custom ResourceDictionary loads some explicitly defined styles (i.e. those loaded from the app at runtime), whereas at runtime it does nothing at all. The IsInDesignMode-Property could be evaluated for this.

Say you have such a class, called 'DesignTimeResourceDictionary', then you just use s.th. like

 <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <Util:DesignTimeResourceDictionary Source="SomeUriToYourResources"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
 </UserControl.Resources>

to load your resources at design-time and make the designer work. At Runtime you can then make your DesignTimeResourceDictionary skip the loading of resources and achieve the desired behavior.

If you need, you could really create a copy of the real resources for this, or you can just create a dummy dictionary containing all the keys you need to keep the designer working.

Simpzon
This is an interesting idea, but it's unfortunate that there's not a more automatic solution.
emddudley