Assigining a TypeConverter to a class you don't own

I ran into problems with the XNA Beta1, where by I had a class that had a Vector2 struct in.  The problem with the XNA Vector2 struct is that there is no TypeConverter for it at the moment.  This means that there is no support in the designer. 

I initially solved this problem by assigning a type converter to the public property on my class that used the Vector2. (see below)

public class A{ private Vector2 v; [TypeConverter(typeof(Vector2Converter))] public Vector2 Vec {  get{ return v; }  set{ v= value} }}

However, VS2005, when serializing out to code from the designer, it will not obey the TypeConverter on the property, but will try to use the Type's Conveter eventhough the designer will use the TypeConverter on your class to edit the control... clear as mud? :)

This leads to ugly code in the InitializeCode method that tries to look in the resource file to get the object out.  I didn't like this solution because it looks ugly and is hard to maintain.

I solved this problem by forcing the TypeConverter on to the Vector2.  In my classes constructor I called the following code I have created.

public static void Register<T, TC>() where TC: TypeConverter{ Attribute[] attr = new Attribute[1]; TypeConverterAttribute vConv = new TypeConverterAttribute(typeof(TC));      attr[0] = vConv; TypeDescriptor.AddAttributes(typeof(T), attr);}

The above code adds the TypeConverter (TC) to the Type (T) so that the designer can serialize to code correctly using my own TypeConverter.  The main thing it is doing is calling: TypeDescriptor.AddAttributes

The solution then allows the Designer to serialize to code and it gets rid of having to serialize the object to a resource file.  The solution would look like the code below.

public class A {  private Vector2 v;   //Enables Designer support, so it can be edited [TypeConverter(typeof(Vector2Converter))]  public Vector2 Vec {   get{ return v; }   set{ v= value}  }  public A() {  //Enables designer serialization to code  ConverterRegistration.Register<Vector2 , Vector2Converter>(); }}

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)