Silverlight 2.0 Beta 1 and WPF Resource Management: What's the same and what's different?

Both Silverlight 2.0 and WPF support the notion of resources, which can be associated with almost any element - in both SL and WPF the widely inherited-from FrameworkElement (and in WPF the FrameworkContentElement) class exposes a Resources property of type ResourceDictionary. The Resources dictionary is a simple collection of key-value pairs. Almost anything can be stored as a resource, from brushes to templates, data sources, converters, dates, strings and any other .NET object which can be represented as XAML. The key used to retrieve resources can be anything too; however strings or static fields are used.

The current (beta 1) implementation of Silverlight 2.0 has some notable differences to WPF however. The first is that resources cannot be factored into separate files and referenced using the <ResourceDictionary.MergedDictionaries> feature of WPF resource dictionaries. This is unfortunate as it means that the App.xaml file will probably become large and unweildy (and potentially an integration pain point between developers and designers) in Silverlight.

Another notable difference is the way resources are retrieved in code. In WPF FrameworkElement and FrameworkContentElement have methods FindResource and TryFindResource which will look for a resource in the current dictionary with the key provided. If no resource is present for this key these methods traverse the logical tree to ancestor nodes looking for the resource that matches the key. Silverlight 2.0 beta 1 does not expose methods like these (possibly due to the de-emphasis of the separation between the visual and logical trees as concepts in its programming model). You can refer to resources on an object by their key, but no tree searching is performed - if the resource doesn't exist in that resource dictionary then null is returned.

As with WPF, resource retrieval in XAML is done using the {StaticResource} markup extension in Silverlight 2.0. When this markup extension is used the tree is traversed looking for a resource with the specified key. There is no {DynamicResource} markup extension in Silverlight 2.0.

In Silverlight 2.0 Resources can either be given a key (by setting the x:Key attribute) or a name (by setting the x:Name attribute) and both will work for item resolution. Attempting to add two elements with the same value (one by setting the key attribute, the other by setting the name attribute) results in a run-time error.