Thursday, September 24, 2009

Guid properties and XAML serialization in Silverlight

Today I found that the XAML parser of Silverlight can’t handle Guids. You need to set a type converter to handle them! In WPF Guid properties are handled automatically.

To get it working you need to add this converter to your project:

   1: public class GuidConverter : TypeConverter
   2: {
   3:     public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   4:     {
   5:         if (sourceType == typeof(string))
   6:         {
   7:             return true;
   8:         }
   9:  
  10:         return base.CanConvertFrom(context, sourceType);
  11:     }
  12:  
  13:     public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
  14:     {
  15:         if (destinationType == typeof(Guid))
  16:         {
  17:             return true;
  18:         }
  19:  
  20:         return base.CanConvertTo(context, destinationType);
  21:     }
  22:  
  23:     public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
  24:     {
  25:         return new Guid((string)value);
  26:     }
  27:  
  28:     public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
  29:     {
  30:         return ((Guid)value).ToString();
  31:     }
  32: }

And them place this on top of the Guid property:

   1: [TypeConverter(typeof(GuidConverter))]
   2: public new Guid SystemId
   3: {
   4:     get;
   5:     set;
   6: }

Works on my machine!

Have fun,

Pedro

No comments: