Sunday, 27 December 2009

Prism Sample: Resources

An area of Prism development that often gets overlooked is the management of resources.  I mentioned in a previous blog that View reuse is unlikely, but that doesn't mean you should create unnecessary dependencies to a resource assembly.

Similar to modules, resource assemblies can have an accompanying interface assembly.  This is done by defining ComponentResourceKeys in your interface assembly and using them as resource keys in your resource dictionary and in your Views.

public static class Styles
    public static ComponentResourceKey LargeTextStyleKey
        get { return new ComponentResourceKey(typeof (Styles), "LargeTextStyle"); }

and in your Xaml...

<textblock text="My Sample TextBlock Style"
           Style="{StaticResource {ComponentResourceKey TypeInTargetAssembly={x:Type Interfaces:Styles}, ResourceId=LargeTextStyleKey}}" />

Taking this approach decouples your modules from the resource assembly.  The advantage to do this is not so much in the area of reuse, but more in the implementation of themes.  Any Views that require the use of a resource can simply refer to it by its ComponentResourceKey.

Additionally, I would only have the Shell load the external resources, since the View modules are now unaware of the external resource.  The only draw back in doing this is you will lose your Visual Designer when editing your Xaml, because the designer cannot resolve the resource to render it.

It is also worth setting up default styles based on control types, by using the control type as the resource key (e.g. {x:Type TextBlock}).  This does not require the use of ComponentResourceKeys.

The area of theming WPF applications is a common one and there are a number of resources on CodePlex which address this area.  One example is the Razre WPF Framework, or you can build your own ThemeManager.

I think this pretty much concludes the PrismSample articles.  This was meant as an introduction for developers starting out with Prism and to provide some guidelines in setting up a Prism solution.  I hope this was of some use.  I'm certain others will have differing opinions, and that's okay too.  I'm always on the hunt for new approaches and new ideas.

I think Prism has a real future in WPF development.  Once you get into it and see the benefits, it changes how you think about and view WPF development; afterwards it is difficult not to think and develop that way, which is a good thing.

As always, comments/feedback welcome...

No comments: