views:

235

answers:

2

I have a question similar to this - Does Silverlight xaml support Byte Data Type. Does silverlight xaml support Guid datatype. I m trying to set Guid in my xaml which is a declared as property in c# class library. is this possible? I tried using

xmlns:sys="clr-namespace:System;assembly=mscorlib"

and using

<sys:Guid>F16095D1-1954-4C33-A856-2BDA87DFD371</sys.Guid>

but that not working !

Please suggest if there is a work around for this.

Thanks in advance
Sai

+1  A: 

A work round would really depend on why you want to include a raw Guid in Xaml in the first place.

You can't use sys:Guid in the way you are attempting to because Xaml has no way to know how to convert the content of the element to an instance of a Guid structure. In fact you can't include an empty sys:Guid although I don't know why you can't do that (not that it would ever be useful to do so anyway).

However if you are trying to assign a value to a property on an instance of a type you control then you can work round this with a type converter. First add a GuidConverter to your project:-

using System;
using System.ComponentModel;
using System.Globalization;

namespace SilverlightApplication1
{
    public class GuidConverter : TypeConverter
    {
     public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
     {
      return sourceType == typeof(string);
     }

     public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
     {
      return destinationType == typeof(string); 
     }

     public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
     {
      return new Guid((string)value);
     }

     public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
     {
      return ((Guid)value).ToString("", culture);
     }

    }
}

Now decorate your type's property with a TypeConverter attribute:

[TypeConverter(typeof(GuidConverter))]
public Guid MyGuidValue {get; set; }

Now in your xaml you can do this:-

<local:MyType MyGuidValue="F16095D1-1954-4C33-A856-2BDA87DFD371" />
AnthonyWJones
Thank you! I will try this!
Sai
A: 

A much simpler solution is to use the sys:string type instead.

I added the following XAML to a Resource dictionary, and had no problems extracting it in C# code:

XAML

<sys:String x:Key="MyGuid">F16095D1-1954-4C33-A856-2BDA87DFD371</sys:String>

C#:

string guidString = Application.Current.Resources["MyGuid"] as string;
Guid guid = new Guid(guidString);

YinYangMoney

Jim McCurdy
Thank you! easy approach but kind of messy...but I will surely try this!
Sai