Skip to content

Instantly share code, notes, and snippets.

@maxfridbe
Created November 15, 2012 17:36
Show Gist options
  • Save maxfridbe/4079991 to your computer and use it in GitHub Desktop.
Save maxfridbe/4079991 to your computer and use it in GitHub Desktop.
Shared Resources
/*
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../../Resources/StringResources.xaml"/>
</ResourceDictionary.MergedDictionaries>
or
<ResourceDictionary.MergedDictionaries>
<local:ResourceDictionaryLocator Assembly="{x:Type Windows:MainWindowStudioFlow}"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
*/
public static Uri GetCurrentUICultureSource(string resourceName, Type containingModule)
{
var name = containingModule.Assembly.GetName().Name;
var cult = Thread.CurrentThread.CurrentUICulture.ToString();
var location = cult == "en-US"
? string.Format("pack://application:,,,/{0};component/Resources/{1}.xaml", name, resourceName)
: string.Format("pack://application:,,,/{0};component/Resources/{1}.{2}.xaml", name, resourceName, cult);
var uri = new Uri(location, UriKind.RelativeOrAbsolute);
return uri;
}
public class ResourceDictionaryLocator : ResourceDictionary
{
private Type _assembly ;
public Type Assembly
{
set
{
_assembly = value;
updateSrc();
}
}
public ResourceDictionaryLocator()
{
ModuleBootstrapper.LanguageChanged += (s) => updateSrc();
}
private void updateSrc()
{
var uriSRC = ModuleBootstrapper.GetCurrentUICultureSource("StringResources", _assembly);
base.Source = uriSRC;
}
}
/// <summary>
/// The shared resource dictionary is a specialized resource dictionary
/// that loads it content only once. If a second instance with the same source
/// is created, it only merges the resources from the cache.
/// </summary>
public class SharedResourceDictionary : ResourceDictionary
{
/// <summary>
/// Internal cache of loaded dictionaries
/// </summary>
public static Dictionary<Uri, ResourceDictionary> _sharedDictionaries =
new Dictionary<Uri, ResourceDictionary>();
/// <summary>
/// Local member of the source uri
/// </summary>
private Uri _sourceUri;
/// <summary>
/// Gets or sets the uniform resource identifier (URI) to load resources from.
/// </summary>
public new Uri Source
{
get { return _sourceUri; }
set
{
_sourceUri = value;
if (!_sharedDictionaries.ContainsKey(value))
{
// If the dictionary is not yet loaded, load it by setting
// the source of the base class
base.Source = value;
// add it to the cache
_sharedDictionaries.Add(value, this);
}
else
{
// If the dictionary is already loaded, get it from the cache
MergedDictionaries.Add(_sharedDictionaries[value]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment