Skip to content

Instantly share code, notes, and snippets.

@airbreather
Created December 4, 2018 20:47
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 airbreather/1ca3ef7698b3539ac3cd1170144a6561 to your computer and use it in GitHub Desktop.
Save airbreather/1ca3ef7698b3539ac3cd1170144a6561 to your computer and use it in GitHub Desktop.
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Reference Include="PresentationFramework" />
<Reference Include="System.Xaml" />
</ItemGroup>
</Project>
using System;
using System.ComponentModel;
using System.Globalization;
// WPF markup types
using WpfXamlReader = System.Windows.Markup.XamlReader;
using WpfXamlWriter = System.Windows.Markup.XamlWriter;
// System.Xaml types
using SystemXamlServices = System.Xaml.XamlServices;
static class Driver
{
static void Main()
{
Ser obj = Ser.CreateFrom("some payload");
// System.Windows.Markup
{
string s = WpfXamlWriter.Save(obj);
Ser obj2 = (Ser)WpfXamlReader.Parse(s);
Console.WriteLine($"obj.Payload: {obj.Payload}");
Console.WriteLine($"obj2.Payload: {obj2.Payload}");
}
// System.Xaml
{
// this line throws immediately:
string s = SystemXamlServices.Save(obj);
Ser obj2 = (Ser)SystemXamlServices.Parse(s);
Console.WriteLine($"obj.Payload: {obj.Payload}");
Console.WriteLine($"obj2.Payload: {obj2.Payload}");
}
}
}
[TypeConverter(typeof(TC))]
public sealed class Ser
{
private Ser(string s) => this.Payload = s;
public string Payload { get; }
public static Ser CreateFrom(string payload) => new Ser(payload);
}
public sealed class TC : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string s
? Ser.CreateFrom(s)
: base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
return destinationType == typeof(string)
? ((Ser)value).Payload
: base.ConvertTo(context, culture, value, destinationType);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment