The Size Type/Property

  • Thread starter Thread starter andre
  • Start date Start date
A

andre

Please, post the complete csharp code to implement a property like the Size
one.
Including the "Width" and "Height" order of appearance in the designer.
Thanks.
 
To do that you need to implement a TypeConverter for your type. I wrote the
following code to show how to do this for at type named Test which has two
properties X and Y (similar to Width and Height of Size):

<code>
[TypeConverter(typeof(TestTypeConverter))]
public struct Test
{
int x;
int y;

public Test(int x, int y)
{
this.x = x;
this.y = y;
}

public int X
{
get { return x; }
set { x = value; }
}

public int Y
{
get { return y; }
set { y = value; }
}
}

public class TestTypeConverter : TypeConverter
{
public TestTypeConverter()
{
}

public override bool CanConvertFrom(ITypeDescriptorContext context,
Type sourceType)
{
if (sourceType == typeof(string))
return true;

return base.CanConvertFrom (context, sourceType);
}

public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
if (destinationType == typeof(InstanceDescriptor))
return true;

return base.CanConvertTo (context, destinationType);
}

public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
if (value is string)
{
string[] v = ((string) value).Split(new char[] {','});
return new Test(int.Parse(v[0]), int.Parse(v[1]));
}
return base.ConvertFrom(context, culture, value);
}

public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (value is Test)
{
if (destinationType == typeof(string))
{
return ((Test) value).X + "," + ((Test) value).Y;
}
else if (destinationType == typeof(InstanceDescriptor))
{
Test t = (Test) value;

ConstructorInfo ctor = typeof(Test).GetConstructor(new
Type[] {typeof(int), typeof(int)});
if (ctor != null)
{
return new InstanceDescriptor(ctor, new object[]
{t.X, t.Y});
}
}
}
return base.ConvertTo(context, culture, value, destinationType);
}

public override bool GetPropertiesSupported(ITypeDescriptorContext
context)
{
return true;
}

public override PropertyDescriptorCollection
GetProperties(ITypeDescriptorContext context, object value, Attribute[]
attributes)
{
return TypeDescriptor.GetProperties(typeof(Test));
}

}

</code>

HTH, Jakob.
 
Back
Top