TryFindResource extension for Silverlight™ with MergedDictionaries support

Here is my attempt to implement a TryFindResource extension method that would work in Silverlight™ supporting MergedDictionaries too, in case you need to build a single client source code base for both WPF and Silverlight™ (otherwise I would have implemented a generic method instead J). Note that it skips Style definitions and browses visual parents, not Framework parent relationships to avoid loop breaks:

internal static class ResourceExtensions
{
  public static object TryFindResource(this FrameworkElement element, object resourceKey)
  {
    var e = element;
    while (e != null)
    {
      var resource = GetResource(e.Resources, resourceKey);
      if (resource != null)
        return resource;
      e = VisualTreeHelper.GetParent(e) as FrameworkElement;
    }
    return GetResource(Application.Current.Resources, resourceKey);
  }
  private static object GetResource(ResourceDictionary resources, object resourceKey)
  {
    var resource = resources[resourceKey];
    if (resource != null)
      return resource;
    foreach (var mergedResources in resources.MergedDictionaries)
    {
      resource = GetResource(mergedResources, resourceKey);
      if (resource != null)
        return resource;
      }
      return null;
    }
  }
}
Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, WPF. Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s