Skip to content

Instantly share code, notes, and snippets.

@SchreinerK
Last active April 22, 2020 09:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SchreinerK/a753cee33a0e791dea6779bce730eade to your computer and use it in GitHub Desktop.
Save SchreinerK/a753cee33a0e791dea6779bce730eade to your computer and use it in GitHub Desktop.
SharedResourceDictionary Simple
using System;
using System.Collections.Generic;
using System.Windows;
namespace KsWare.Gist {
// https://gist.github.com/SchreinerK/a753cee33a0e791dea6779bce730eade
public class SharedResourceDictionary : ResourceDictionary {
private static readonly Dictionary<Uri, WeakReference> SharedCache = new Dictionary<Uri, WeakReference>();
private Uri _sourceCore;
public SharedResourceDictionary() {
}
public bool DisableCache { get; set; }
public new Uri Source {
get => _sourceCore;
set {
_sourceCore = value;
if (!SharedCache.ContainsKey(_sourceCore) || DisableCache) {
base.Source = _sourceCore;
if (DisableCache) return;
CacheSource();
}
else {
ResourceDictionary target = (ResourceDictionary) SharedCache[_sourceCore].Target;
if (target != null) {
MergedDictionaries.Add(target);
_sourceCore = target.Source;
}
else {
base.Source = _sourceCore;
CacheSource();
}
}
}
}
private void CacheSource() {
if (SharedCache.ContainsKey(_sourceCore)) SharedCache.Remove(_sourceCore);
SharedCache.Add(_sourceCore, new WeakReference((object) this, false));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment