Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Reflection;
- using System.Xaml;
- using System.Xaml.Schema;
- namespace Sandbox
- {
- public class Foo
- {
- public object DataContext { get; set; }
- }
- class Program
- {
- private static XamlDirective DesignContextDirective = new XamlDirective(
- new[] { "http://schemas.microsoft.com/expression/blend/2008" },
- "DataContext", XamlLanguage.Object, null, AllowedMemberLocations.Attribute);
- class CustomContext : XamlSchemaContext
- {
- public bool IsDesignMode { get; set; }
- public override XamlDirective GetXamlDirective(string xamlNamespace, string name)
- {
- if (IsDesignMode && name == DesignContextDirective.Name && xamlNamespace == DesignContextDirective.PreferredXamlNamespace)
- {
- return DesignContextDirective;
- }
- return base.GetXamlDirective(xamlNamespace, name);
- }
- public override bool TryGetCompatibleXamlNamespace(string xamlNamespace, out string compatibleNamespace)
- {
- //Forces XamlXmlReader to not ignore our namespace if mc:Ignorable is set
- if (
- IsDesignMode &&
- xamlNamespace == DesignContextDirective.PreferredXamlNamespace)
- {
- compatibleNamespace = xamlNamespace;
- return true;
- }
- return base.TryGetCompatibleXamlNamespace(xamlNamespace, out compatibleNamespace);
- }
- }
- class CustomWriter : XamlObjectWriter
- {
- public bool IsDesignMode { get; set; }
- private static PropertyInfo DataContextProperty = typeof(Foo).GetProperty("DataContext");
- public CustomWriter(XamlSchemaContext schemaContext) : base(schemaContext)
- {
- }
- public override void WriteStartMember(XamlMember property)
- {
- if (IsDesignMode && property == DesignContextDirective)
- base.WriteStartMember(new XamlMember(DataContextProperty, SchemaContext));
- else
- base.WriteStartMember(property);
- }
- }
- static void Main(string[] args)
- {
- foreach (var designMode in new[] {true, false})
- {
- XamlXmlReaderSettings settings = new XamlXmlReaderSettings {LocalAssembly = typeof(Foo).Assembly};
- var rdr = new XamlXmlReader(new StringReader(@"
- <Foo xmlns='clr-namespace:Sandbox'
- xmlns:d='http://schemas.microsoft.com/expression/blend/2008'
- xmlns:mc='http://schemas.openxmlformats.org/markup-compatibility/2006'
- mc:Ignorable='d'
- d:DataContext='wat'>
- </Foo>"), new CustomContext(){IsDesignMode = designMode}, settings);
- var writer = new CustomWriter(rdr.SchemaContext){IsDesignMode = designMode};
- XamlServices.Transform(rdr, writer);
- var obj = (Foo) writer.Result;
- Console.WriteLine($"DesignMode: {designMode}, DataContext: {obj.DataContext}");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement