Last active
September 1, 2018 10:35
-
-
Save jeiea/0cc60143f2ba221ba18ff08d1a8dd259 to your computer and use it in GitHub Desktop.
A utility for importing separate xaml files while previewing it in xaml editor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.ComponentModel; | |
using System.IO; | |
using System.Windows; | |
using System.Windows.Markup; | |
/// <summary> | |
/// A utility for importing separate xaml files while previewing it in xaml editor. | |
/// </summary> | |
// <example> | |
// <Window.Resources> | |
// <ResourceDictionary> | |
// <ResourceDictionary.MergedDictionaries> | |
// <local:FlatDictionary Key = "Import" DesignSource="pack://application,,,/res/Import.xaml"/> | |
// </ResourceDictionary.MergedDictionaries> | |
// </ResourceDictionary> | |
// </Window.Resources> | |
public class FlatDictionary : ResourceDictionary, ISupportInitialize { | |
// TODO: It seems to be able to support autocomplete by EndInit() and | |
// LoadComponent(object, Uri), but have limitation from | |
// Application.LoadComponent that cannot reference other assembly. | |
private class Proxy { } | |
private string _Key; | |
public string Key { | |
get { return _Key; } | |
set { | |
_Key = value; | |
if (DesignSource != null) { | |
Register(); | |
} | |
} | |
} | |
private Uri _DesignSource; | |
public Uri DesignSource { | |
get { return _DesignSource; } | |
set { | |
_DesignSource = value; | |
if (Key != null) { | |
Register(); | |
} | |
} | |
} | |
private void Register() { | |
this[Key] = new Proxy(); | |
} | |
protected override void OnGettingValue(object key, ref object value, out bool canCache) { | |
if (value is Proxy) { | |
value = LoadComponent(DesignSource); | |
canCache = false; | |
} | |
else { | |
base.OnGettingValue(key, ref value, out canCache); | |
} | |
} | |
private object LoadComponent(Uri uri) { | |
if (uri == null) { | |
return null; | |
} | |
if (uri.OriginalString.Length >= 2 && uri.OriginalString[1] == ':') { | |
using (var f = new FileStream(uri.OriginalString, FileMode.Open)) { | |
return XamlReader.Load(f); | |
} | |
} | |
Uri relUri; | |
if (uri.OriginalString.StartsWith("pack:")) { | |
relUri = new Uri($";component{uri.AbsolutePath}", UriKind.Relative); | |
} | |
else { | |
relUri = uri; | |
} | |
return Application.LoadComponent(relUri); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment