public XamlObjectWriter (XamlSchemaContext schemaContext, XamlObjectWriterSettings settings) { if (schemaContext == null) throw new ArgumentNullException ("schemaContext"); this.sctx = schemaContext; this.settings = settings ?? new XamlObjectWriterSettings (); }
public static object LoadDeferredContent(System.Xaml.XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, Object rootObject, XamlObjectWriterSettings parentSettings, Uri baseUri) { XamlObjectWriterSettings settings = XamlReader.CreateObjectWriterSettings(parentSettings); // Don't set settings.RootObject because this isn't the real root return Load(xamlReader, writerFactory, skipJournaledProperties, rootObject, settings, baseUri); }
public XamlObjectWriter(XamlSchemaContext schemaContext, XamlObjectWriterSettings settings) { if (schemaContext == null) { throw new ArgumentNullException("schemaContext"); } this.Initialize(schemaContext, null, settings); }
public XamlObjectWriter (XamlSchemaContext schemaContext, XamlObjectWriterSettings settings) { if (schemaContext == null) throw new ArgumentNullException ("schemaContext"); this.sctx = schemaContext; this.settings = settings ?? new XamlObjectWriterSettings (); var manager = new XamlWriterStateManager<XamlObjectWriterException, XamlObjectWriterException> (false); intl = new XamlObjectWriterInternal (this, sctx, manager); }
public XamlObjectWriter (XamlSchemaContext schemaContext, XamlObjectWriterSettings settings) { if (schemaContext == null) throw new ArgumentNullException ("schemaContext"); this.sctx = schemaContext; this.settings = settings ?? new XamlObjectWriterSettings (); var p = new PrefixLookup (sctx); service_provider = new ValueSerializerContext (p, sctx); namespaces = p.Namespaces; }
internal XamlObjectWriter(XamlSavedContext savedContext, XamlObjectWriterSettings settings) { if (savedContext == null) { throw new ArgumentNullException("savedContext"); } if (savedContext.SchemaContext == null) { throw new ArgumentException(System.Xaml.SR.Get("SavedContextSchemaContextNull"), "savedContext"); } this.Initialize(savedContext.SchemaContext, savedContext, settings); }
internal XamlObjectWriterSettings StripDelegates() { XamlObjectWriterSettings result = new XamlObjectWriterSettings(this); // We need better protection against leaking out these delegates result.AfterBeginInitHandler = null; result.AfterEndInitHandler = null; result.AfterPropertiesHandler = null; result.BeforePropertiesHandler = null; #if !TARGETTING35SP1 result.XamlSetValueHandler = null; #endif return(result); }
public XamlObjectWriterSettings(XamlObjectWriterSettings settings) { var s = settings; AfterBeginInitHandler = s.AfterBeginInitHandler; AfterEndInitHandler = s.AfterEndInitHandler; AfterPropertiesHandler = s.AfterPropertiesHandler; BeforePropertiesHandler = s.BeforePropertiesHandler; ExternalNameScope = s.ExternalNameScope; IgnoreCanConvert = s.IgnoreCanConvert; PreferUnconvertedDictionaryKeys = s.PreferUnconvertedDictionaryKeys; RegisterNamesOnExternalNamescope = s.RegisterNamesOnExternalNamescope; RootObjectInstance = s.RootObjectInstance; SkipDuplicatePropertyCheck = s.SkipDuplicatePropertyCheck; SkipProvideValueOnRoot = s.SkipProvideValueOnRoot; XamlSetValueHandler = s.XamlSetValueHandler; }
public void DefaultValues () { var s = new XamlObjectWriterSettings (); Assert.IsNull (s.AccessLevel, "#1"); Assert.IsNull (s.AfterBeginInitHandler, "#2"); Assert.IsNull (s.AfterEndInitHandler, "#3"); Assert.IsNull (s.AfterPropertiesHandler, "#4"); Assert.IsNull (s.BeforePropertiesHandler, "#5"); Assert.IsNull (s.ExternalNameScope, "#6"); Assert.IsFalse (s.IgnoreCanConvert, "#7"); Assert.IsFalse (s.PreferUnconvertedDictionaryKeys, "#8"); Assert.IsFalse (s.RegisterNamesOnExternalNamescope, "#9"); Assert.IsNull (s.RootObjectInstance, "#10"); Assert.IsFalse (s.SkipDuplicatePropertyCheck, "#11"); Assert.IsFalse (s.SkipProvideValueOnRoot, "#12"); Assert.IsNull (s.XamlSetValueHandler, "#13"); }
/// <summary> /// Loads XAML from the specified XamlXmlReader and returns the deserialized object. Any event handlers /// are bound to methods defined in the provided Scope and converted using the provided DynamicOperations /// object. /// </summary> public static object LoadComponent(dynamic scope, DynamicOperations operations, XamlXmlReader reader) { var settings = new XamlObjectWriterSettings(); settings.RootObjectInstance = scope; var myWriter = new DynamicWriter((object)scope, operations, reader.SchemaContext, settings); while (reader.Read()) { myWriter.WriteNode(reader); } foreach (string name in myWriter.Names) { object value = myWriter.RootNameScope.FindName(name); if (value != null) { operations.SetMember((object)scope, name, value); } } return myWriter.Result; }
public XamlObjectWriterSettings (XamlObjectWriterSettings settings) : base (settings) { var s = settings; AccessLevel = s.AccessLevel; AfterBeginInitHandler = s.AfterBeginInitHandler; AfterEndInitHandler = s.AfterEndInitHandler; AfterPropertiesHandler = s.AfterPropertiesHandler; BeforePropertiesHandler = s.BeforePropertiesHandler; ExternalNameScope = s.ExternalNameScope; IgnoreCanConvert = s.IgnoreCanConvert; PreferUnconvertedDictionaryKeys = s.PreferUnconvertedDictionaryKeys; RegisterNamesOnExternalNamescope = s.RegisterNamesOnExternalNamescope; RootObjectInstance = s.RootObjectInstance; SkipDuplicatePropertyCheck = s.SkipDuplicatePropertyCheck; SkipProvideValueOnRoot = s.SkipProvideValueOnRoot; XamlSetValueHandler = s.XamlSetValueHandler; }
public XamlObjectWriterSettings(XamlObjectWriterSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } this.AfterBeginInitHandler = settings.AfterBeginInitHandler; this.BeforePropertiesHandler = settings.BeforePropertiesHandler; this.AfterPropertiesHandler = settings.AfterPropertiesHandler; this.AfterEndInitHandler = settings.AfterEndInitHandler; this.XamlSetValueHandler = settings.XamlSetValueHandler; this.RootObjectInstance = settings.RootObjectInstance; this.IgnoreCanConvert = settings.IgnoreCanConvert; this.ExternalNameScope = settings.ExternalNameScope; this.SkipDuplicatePropertyCheck = settings.SkipDuplicatePropertyCheck; this.RegisterNamesOnExternalNamescope = settings.RegisterNamesOnExternalNamescope; this.AccessLevel = settings.AccessLevel; this.SkipProvideValueOnRoot = settings.SkipProvideValueOnRoot; this.PreferUnconvertedDictionaryKeys = settings.PreferUnconvertedDictionaryKeys; }
public void RootObjectInstance () { // bug #689548 var obj = new RootObjectInstanceTestClass (); RootObjectInstanceTestClass result; var rsettings = new XamlXmlReaderSettings (); var xml = String.Format (@"<RootObjectInstanceTestClass Property=""Test"" xmlns=""clr-namespace:MonoTests.System.Xaml;assembly={0}""></RootObjectInstanceTestClass>", GetType ().Assembly.GetName ().Name); using (var reader = new XamlXmlReader (new StringReader (xml), rsettings)) { var wsettings = new XamlObjectWriterSettings (); wsettings.RootObjectInstance = obj; using (var writer = new XamlObjectWriter (reader.SchemaContext, wsettings)) { XamlServices.Transform (reader, writer, false); result = (RootObjectInstanceTestClass) writer.Result; } } Assert.AreEqual (obj, result, "#1"); Assert.AreEqual ("Test", obj.Property, "#2"); }
public XamlObjectWriterSettings(XamlObjectWriterSettings settings) { if (settings == null) { throw new ArgumentNullException("settings"); } AfterBeginInitHandler = settings.AfterBeginInitHandler; BeforePropertiesHandler = settings.BeforePropertiesHandler; AfterPropertiesHandler = settings.AfterPropertiesHandler; AfterEndInitHandler = settings.AfterEndInitHandler; #if !TARGETTING35SP1 XamlSetValueHandler = settings.XamlSetValueHandler; #endif RootObjectInstance = settings.RootObjectInstance; IgnoreCanConvert = settings.IgnoreCanConvert; ExternalNameScope = settings.ExternalNameScope; SkipDuplicatePropertyCheck = settings.SkipDuplicatePropertyCheck; RegisterNamesOnExternalNamescope = settings.RegisterNamesOnExternalNamescope; AccessLevel = settings.AccessLevel; SkipProvideValueOnRoot = settings.SkipProvideValueOnRoot; PreferUnconvertedDictionaryKeys = settings.PreferUnconvertedDictionaryKeys; SourceBamlUri = settings.SourceBamlUri; }
private XamlRuntime CreateRuntime(XamlObjectWriterSettings settings, XamlSchemaContext schemaContext) { XamlRuntime runtime = null; XamlRuntimeSettings runtimeSettings = null; if (settings != null) { runtimeSettings = new XamlRuntimeSettings { IgnoreCanConvert = settings.IgnoreCanConvert }; if (settings.AccessLevel != null) { runtime = new PartialTrustTolerantRuntime(runtimeSettings, settings.AccessLevel, schemaContext); } } if (runtime == null) { runtime = new ClrObjectRuntime(runtimeSettings, true); } runtime.LineInfo = this; return runtime; }
private object LoadAsync(XmlReader reader, ParserContext parserContext) { if (reader == null) { throw new ArgumentNullException("reader"); } if (parserContext == null) { parserContext = new ParserContext(); } _xmlReader = reader; object rootObject = null; if (parserContext.BaseUri == null || String.IsNullOrEmpty(parserContext.BaseUri.ToString())) { if (reader.BaseURI == null || String.IsNullOrEmpty(reader.BaseURI.ToString())) { parserContext.BaseUri = BaseUriHelper.PackAppBaseUri; } else { parserContext.BaseUri = new Uri(reader.BaseURI); } } _baseUri = parserContext.BaseUri; System.Xaml.XamlXmlReaderSettings settings = new System.Xaml.XamlXmlReaderSettings(); settings.IgnoreUidsOnPropertyElements = true; settings.BaseUri = parserContext.BaseUri; settings.ProvideLineInfo = true; XamlSchemaContext schemaContext = parserContext.XamlTypeMapper != null ? parserContext.XamlTypeMapper.SchemaContext : GetWpfSchemaContext(); try { _textReader = new System.Xaml.XamlXmlReader(reader, schemaContext, settings); _stack = new XamlContextStack <WpfXamlFrame>(() => new WpfXamlFrame()); System.Xaml.XamlObjectWriterSettings objectSettings = XamlReader.CreateObjectWriterSettings(); objectSettings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args) { if (rootObject == null) { rootObject = args.Instance; _styleConnector = rootObject as IStyleConnector; } UIElement uiElement = args.Instance as UIElement; if (uiElement != null) { uiElement.SetPersistId(_persistId++); } DependencyObject dObject = args.Instance as DependencyObject; if (dObject != null && _stack.CurrentFrame.XmlnsDictionary != null) { XmlnsDictionary dictionary = _stack.CurrentFrame.XmlnsDictionary; dictionary.Seal(); XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary); } }; _objectWriter = new System.Xaml.XamlObjectWriter(_textReader.SchemaContext, objectSettings); _parseCancelled = false; _skipJournaledProperties = parserContext.SkipJournaledProperties; XamlMember synchronousModeProperty = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "SynchronousMode"); XamlMember synchronousRecordProperty = _textReader.SchemaContext.GetXamlDirective("http://schemas.microsoft.com/winfx/2006/xaml", "AsyncRecords"); System.Xaml.XamlReader xamlReader = _textReader; IXamlLineInfo xamlLineInfo = xamlReader as IXamlLineInfo; IXamlLineInfoConsumer xamlLineInfoConsumer = _objectWriter as IXamlLineInfoConsumer; bool shouldPassLineNumberInfo = false; if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) && (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)) { shouldPassLineNumberInfo = true; } bool async = false; bool lastPropWasSyncMode = false; bool lastPropWasSyncRecords = false; while (!_textReader.IsEof) { WpfXamlLoader.TransformNodes(xamlReader, _objectWriter, true /*onlyLoadOneNode*/, _skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, _stack, _styleConnector); if (xamlReader.NodeType == System.Xaml.XamlNodeType.StartMember) { if (xamlReader.Member == synchronousModeProperty) { lastPropWasSyncMode = true; } else if (xamlReader.Member == synchronousRecordProperty) { lastPropWasSyncRecords = true; } } else if (xamlReader.NodeType == System.Xaml.XamlNodeType.Value) { if (lastPropWasSyncMode == true) { if (xamlReader.Value as String == "Async") { async = true; } } else if (lastPropWasSyncRecords == true) { if (xamlReader.Value is int) { _maxAsynxRecords = (int)xamlReader.Value; } else if (xamlReader.Value is String) { _maxAsynxRecords = Int32.Parse(xamlReader.Value as String, TypeConverterHelper.InvariantEnglishUS); } } } else if (xamlReader.NodeType == System.Xaml.XamlNodeType.EndMember) { lastPropWasSyncMode = false; lastPropWasSyncRecords = false; } if (async && rootObject != null) { break; } } } catch (Exception e) { // Don't wrap critical exceptions or already-wrapped exceptions. if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !ShouldReWrapException(e, parserContext.BaseUri)) { throw; } RewrapException(e, parserContext.BaseUri); } if (!_textReader.IsEof) { Post(); //ThreadStart threadStart = new ThreadStart(ReadXamlAsync); //Thread thread = new Thread(threadStart); //thread.Start(); } else { TreeBuildComplete(); } if (rootObject is DependencyObject) { if (parserContext.BaseUri != null && !String.IsNullOrEmpty(parserContext.BaseUri.ToString())) { (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, parserContext.BaseUri); } //else // (rootObject as DependencyObject).SetValue(BaseUriHelper.BaseUriProperty, BaseUriHelper.PackAppBaseUri); WpfXamlLoader.EnsureXmlNamespaceMaps(rootObject, schemaContext); } Application app = rootObject as Application; if (app != null) { app.ApplicationMarkupBaseUri = GetBaseUri(settings.BaseUri); } return(rootObject); }
public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings) { return new XamlObjectWriter(new XamlSchemaContext()); }
private void ExtractBAML(string name, Stream stream) { var reader = new Baml2006Reader(stream); var settings = new XamlObjectWriterSettings (); settings.BeforePropertiesHandler += (sender, e) => { Trace("properties for {0}", e.Instance); }; settings.XamlSetValueHandler += (sender, e) => { //TraceTarget.Trace("set value {0} = {1}", e.Member.Name, e.Value); /*if (e.Member.Name == "DeferrableContent") { e.Handled = true; }*/ }; var writer = new XamlObjectWriter(reader.SchemaContext, settings); while (reader.Read()) { writer.WriteNode(reader); } var x = writer.Result; var ms = new MemoryStream(); using (var xwriter = XmlWriter.Create(ms, new XmlWriterSettings { Indent = true })) { System.Windows.Markup.XamlWriter.Save(x, xwriter); } var xamlname = Path.ChangeExtension(name, ".xaml"); ms.Position = 0; AddResource(xamlname, ms); }
public XamlObjectWriterFactory(ObjectWriterContext context) { this._savedContext = context.GetSavedContext(SavedContextType.Template); this._parentSettings = context.ServiceProvider_GetSettings(); }
public XamlObjectWriter(XamlSchemaContext schemaContext, XamlObjectWriterSettings settings) : this(schemaContext, settings, null) { }
public DynamicWriter(object scope, DynamicOperations operations, XamlSchemaContext context, XamlObjectWriterSettings settings) : base(context, settings) { _scope = scope; _operations = operations; }
internal static XamlObjectWriterSettings CreateObjectWriterSettings() { XamlObjectWriterSettings owSettings = new XamlObjectWriterSettings(); owSettings.IgnoreCanConvert = true; owSettings.PreferUnconvertedDictionaryKeys = true; return owSettings; }
internal static XamlObjectWriterSettings CreateObjectWriterSettings(XamlObjectWriterSettings parentSettings) { XamlObjectWriterSettings owSettings = CreateObjectWriterSettings(); if (parentSettings != null) { owSettings.SkipDuplicatePropertyCheck = parentSettings.SkipDuplicatePropertyCheck; owSettings.AccessLevel = parentSettings.AccessLevel; owSettings.SkipProvideValueOnRoot = parentSettings.SkipProvideValueOnRoot; } return owSettings; }
private void Initialize(XamlSchemaContext schemaContext, XamlSavedContext savedContext, XamlObjectWriterSettings settings) { this._inDispose = false; if (schemaContext == null) { throw new ArgumentNullException("schemaContext"); } if ((savedContext != null) && (schemaContext != savedContext.SchemaContext)) { throw new ArgumentException(System.Xaml.SR.Get("SavedContextSchemaContextMismatch"), "schemaContext"); } if (settings != null) { this._afterBeginInitHandler = settings.AfterBeginInitHandler; this._beforePropertiesHandler = settings.BeforePropertiesHandler; this._afterPropertiesHandler = settings.AfterPropertiesHandler; this._afterEndInitHandler = settings.AfterEndInitHandler; this._xamlSetValueHandler = settings.XamlSetValueHandler; this._rootObjectInstance = settings.RootObjectInstance; this._skipDuplicatePropertyCheck = settings.SkipDuplicatePropertyCheck; this._skipProvideValueOnRoot = settings.SkipProvideValueOnRoot; this._preferUnconvertedDictionaryKeys = settings.PreferUnconvertedDictionaryKeys; } INameScope rootNameScope = (settings != null) ? settings.ExternalNameScope : null; XamlRuntime runtime = this.CreateRuntime(settings, schemaContext); if (savedContext != null) { this._context = new ObjectWriterContext(savedContext, settings, rootNameScope, runtime); } else { if (schemaContext == null) { throw this.WithLineInfo(new XamlInternalException()); } this._context = new ObjectWriterContext(schemaContext, settings, rootNameScope, runtime); this._context.AddNamespacePrefix("xml", "http://www.w3.org/XML/1998/namespace"); } this._context.IsInitializedCallback = this; this._deferringWriter = new DeferringWriter(this._context); this._rootNamescope = null; }
public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings) { return(new XamlObjectWriter(sctx, settings)); }
public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings) { return new XamlObjectWriter(this._savedContext, settings); }
private static object Load(System.Xaml.XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, bool skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri) { XamlObjectWriter xamlWriter = null; XamlContextStack<WpfXamlFrame> stack = new XamlContextStack<WpfXamlFrame>(() => new WpfXamlFrame()); int persistId = 1; settings.AfterBeginInitHandler = delegate(object sender, System.Xaml.XamlObjectEventArgs args) { if (EventTrace.IsEnabled(EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose)) { IXamlLineInfo ixli = xamlReader as IXamlLineInfo; int lineNumber = -1; int linePosition = -1; if (ixli != null && ixli.HasLineInfo) { lineNumber = ixli.LineNumber; linePosition = ixli.LinePosition; } EventTrace.EventProvider.TraceEvent( EventTrace.Event.WClientParseXamlBamlInfo, EventTrace.Keyword.KeywordXamlBaml | EventTrace.Keyword.KeywordPerf, EventTrace.Level.Verbose, args.Instance == null ? 0 : PerfService.GetPerfElementID(args.Instance), lineNumber, linePosition); } UIElement uiElement = args.Instance as UIElement; if (uiElement != null) { uiElement.SetPersistId(persistId++); } DependencyObject dObject = args.Instance as DependencyObject; if (dObject != null && stack.CurrentFrame.XmlnsDictionary != null) { XmlnsDictionary dictionary = stack.CurrentFrame.XmlnsDictionary; dictionary.Seal(); XmlAttributeProperties.SetXmlnsDictionary(dObject, dictionary); } stack.CurrentFrame.Instance = args.Instance; }; if (writerFactory != null) { xamlWriter = writerFactory.GetXamlObjectWriter(settings); } else { xamlWriter = new System.Xaml.XamlObjectWriter(xamlReader.SchemaContext, settings); } IXamlLineInfo xamlLineInfo = null; try { //Handle Line Numbers xamlLineInfo = xamlReader as IXamlLineInfo; IXamlLineInfoConsumer xamlLineInfoConsumer = xamlWriter as IXamlLineInfoConsumer; bool shouldPassLineNumberInfo = false; if ((xamlLineInfo != null && xamlLineInfo.HasLineInfo) && (xamlLineInfoConsumer != null && xamlLineInfoConsumer.ShouldProvideLineInfo)) { shouldPassLineNumberInfo = true; } IStyleConnector styleConnector = rootObject as IStyleConnector; TransformNodes(xamlReader, xamlWriter, false /*onlyLoadOneNode*/, skipJournaledProperties, shouldPassLineNumberInfo, xamlLineInfo, xamlLineInfoConsumer, stack, styleConnector); xamlWriter.Close(); return xamlWriter.Result; } catch (Exception e) { // Don't wrap critical exceptions or already-wrapped exceptions. if (MS.Internal.CriticalExceptions.IsCriticalException(e) || !XamlReader.ShouldReWrapException(e, baseUri)) { throw; } XamlReader.RewrapException(e, xamlLineInfo, baseUri); return null; // this should never be executed } }
public XamlObjectWriter GetXamlObjectWriter(XamlObjectWriterSettings settings) { var xamlSchemaContext = new XamlSchemaContext(); var xamlObjectWriter = new XamlObjectWriter(xamlSchemaContext, settings); return xamlObjectWriter; }
/// <summary> /// Gets a <see cref="FrameworkTemplate"/> based on the specified parameters. /// </summary> /// <param name="xmlElement">The xml element to get template xaml from.</param> /// <param name="parentObject">The <see cref="XamlObject"/> to use as source for resources and contextual information.</param> /// <returns>A <see cref="FrameworkTemplate"/> based on the specified parameters.</returns> public static FrameworkTemplate GetFrameworkTemplate(XmlElement xmlElement, XamlObject parentObject) { var nav = xmlElement.CreateNavigator(); var ns = new Dictionary<string, string>(); while (true) { var nsInScope = nav.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); foreach (var ak in nsInScope) { if (!ns.ContainsKey(ak.Key) && ak.Key != "") ns.Add(ak.Key, ak.Value); } if (!nav.MoveToParent()) break; } xmlElement = (XmlElement)xmlElement.CloneNode(true); foreach (var dictentry in ns.ToList()) { var value = dictentry.Value; if (value.StartsWith("clr-namespace") && !value.Contains(";assembly=")) { if (!string.IsNullOrEmpty(parentObject.OwnerDocument.CurrentProjectAssemblyName)) { value += ";assembly=" + parentObject.OwnerDocument.CurrentProjectAssemblyName; } } xmlElement.SetAttribute("xmlns:" + dictentry.Key, value); } var keyAttrib = xmlElement.GetAttribute("Key", XamlConstants.XamlNamespace); if (string.IsNullOrEmpty(keyAttrib)) { xmlElement.SetAttribute("Key", XamlConstants.XamlNamespace, "$$temp&&§§%%__"); } var xaml = xmlElement.OuterXml; xaml = "<ResourceDictionary xmlns=\"http://schemas.microsoft.com/netfx/2007/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">" + xaml + "</ResourceDictionary>"; StringReader stringReader = new StringReader(xaml); XmlReader xmlReader = XmlReader.Create(stringReader); var xamlReader = new XamlXmlReader(xmlReader, parentObject.ServiceProvider.SchemaContext); var seti = new XamlObjectWriterSettings(); var resourceDictionary = new ResourceDictionary(); var obj = parentObject; while (obj != null) { if (obj.Instance is ResourceDictionary) { var r = obj.Instance as ResourceDictionary; foreach (var k in r.Keys) { if (!resourceDictionary.Contains(k)) resourceDictionary.Add(k, r[k]); } } else if (obj.Instance is FrameworkElement) { var r = ((FrameworkElement)obj.Instance).Resources; foreach (var k in r.Keys) { if (!resourceDictionary.Contains(k)) resourceDictionary.Add(k, r[k]); } } obj = obj.ParentObject; } seti.BeforePropertiesHandler = (s, e) => { if (seti.BeforePropertiesHandler != null) { var rr = e.Instance as ResourceDictionary; rr.MergedDictionaries.Add(resourceDictionary); seti.BeforePropertiesHandler = null; } }; var writer = new XamlObjectWriter(parentObject.ServiceProvider.SchemaContext, seti); XamlServices.Transform(xamlReader, writer); var result = (ResourceDictionary)writer.Result; var enr = result.Keys.GetEnumerator(); enr.MoveNext(); var rdKey = enr.Current; var template = result[rdKey] as FrameworkTemplate; result.Remove(rdKey); return template; }