views:

228

answers:

2

How can I do this?

Tried using a TypeConverter, but the only thing I could think of was to construct the XML for the types, which doesn't quite cut it. TypeConverters in xaml serialization will escape xml and treat it like plain text. Value converters aren't much better.

Now, I'm moving to ISupportInitialize and will throw if changes are made after initialization, but I would have liked the immutable route...


Example of a type I wish to serialize:

public struct Foo
{
  public string Bar {get;private set;}
  public Foo(string bar) : this()
  {
    Bar = bar;
  }
}

and the code

var foo = new Foo("lol");
var serializedFoo = XamlWriter.Save(foo);
+2  A: 

Sorry, you can't use normal serialization with immutable objects in XAML 2006.

With XAML 2009, which supports constructors and factory methods, you should be able to acomplish your goal. Just be warned, WPF 4 will not be using XAML 2009.

Jonathan Allen
+1  A: 

Doh! I completely misread this question...
=================================

Try using a markup extension to create your immutable struct:

public class FooExtension : MarkupExtension
{
  public string Bar {get; set;}

  public ImgPathExtension(string bar)
  {
    this.Bar = bar;
  }

  public override object ProvideValue(IServiceProvider serviceProvider)
  {
    var foo = new Foo(this.Bar);
    return foo;
  }
}

Now, you can use it in your XAML with the extension syntax: {ext:Foo Bar="lol"}

Just use it the same way you would use any other MarkupExtension, such as Binding, DynamicResource, etc.

See this link if you need more details.

HTH,

Charles

Charles
This can be used when deserializing hand-written XAML, but XAML _serialization_ (i.e. `XamlWriter.Save`) won't know how to use this.
Pavel Minaev
The XAML serializer won't know to use the markup extension...
Thomas Levesque
Yep, I just realized my mistake... Sorry about that.
Charles