How to work with TypeConverter

  • Thread starter Thread starter NicolasC
  • Start date Start date
N

NicolasC

Guest
Hi guys, hope you're all safe and healthy.

Considering the following class:

public class MyPlace : Base
{
public short id;
[DataType]
public short ID
{
get => id;
set { id = value; FirePropertyChanged("ID"); }
}

public string code;
[DataType]
public string Code
{
get => code;
set { code = value; FirePropertyChanged("Code"); }
}

public string label;
[DataType]
public string Label
{
get => label;
set { label = value; FirePropertyChanged("Label"); }
}

IPAddress network;
[DataType]
[TypeConverter(typeof(DataType.ConverterIpAddress))]
public IPAddress Network
{
get => network;
set { network = value; FirePropertyChanged("Network"); }
}
}

And the fllowing TypeConverter:

public class ConverterIpAddress : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
=> sourceType == typeof(string) || sourceType == typeof(byte[]);

public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value == null) return null;
if (value is string) return IPAddress.Parse(value.ToString());
else if (value is byte[]) return new IPAddress(value as byte[]);
else return null;
}

public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
=> destinationType == typeof(string) || destinationType == typeof(byte[]);

public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (value == null || !(value is IPAddress)) return null;
if (destinationType == typeof(string)) return (value as IPAddress).ToString();
else if (destinationType == typeof(byte[])) return (value as IPAddress).GetAddressBytes();
else return null;
}
}

I'd like to be able to set the property Network by reflection with a string as input that would be automatically converted to an IPaddress.

var place = new MyPlace();
place.Code = "NY";
place.Label = "New-York";

var type = place.GetType();
var propertyNetwork = type.GetProperty("Network");
propertyNetwork.SetValue(place, "192.168.1.1");
The output is: Object of type 'System.String' cannot be converted to type 'System.Net.IPAddress'.


So 2 questions:

  • Is this the TypeConverter's purpose?
  • If yes, how can I implement properly? I'm sure I did something wrong...

Thank you in advance for your suggestions

Continue reading...
 
Back
Top