views:

43

answers:

1

One problem bugged me enough to register on stackoverflow. Currently if I want to serialize Color to XML string as named color, or #rrggbb, or #aarrggbb, i do it like this:

[XmlIgnore()]
public Color color;

[XmlElement(ElementName = "Color")]
public String color_XmlSurrogate
{
  get { return MyColorConverter.SetColor(color); }
  set { MyColorConverter.GetColor(value); }
}

Here MyColorConverter does serialization just the way I like it. But all this feels like a kludge, with additional field and all. Is there a way to make it work in less lines, maybe connecting TypeDescriptor with C# attributes related to xml?

+1  A: 

A pain, isn't it? That is all you can do with XmlSerializer, unless you implement IXmlSerializable (which I do not recommend). Options:

  • stick with that, but also mark color_XmlSurrogate as [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)] - that will stop it appearing in most data-binding views, and in the code-editor when referencing your assembly as a dll
  • use DataContractSerializer, which supports private properties (but which doesn't support xml attributes; you can't win...)

btw, I'd have color as a property, not a field:

[XmlIgnore]
public Color Color {get;set;}
Marc Gravell