Passing a context containing properties to a TypeConverter
See the question and my original answer on StackOverflowThe method you want to use is clearly this overload: TypeConverter.ConvertFrom Method (ITypeDescriptorContext, CultureInfo, Object)
It will allow you to pass a pretty generic context. The Instance
property represents the object instance you're working on, and the PropertyDescriptor
property represents the property definition of the property value being converted.
For example, the Winforms property grid does exactly that.
So, you'll have to provide your own context. Here is a sample one:
public class MyContext : ITypeDescriptorContext
{
public MyContext(object instance, string propertyName)
{
Instance = instance;
PropertyDescriptor = TypeDescriptor.GetProperties(instance)[propertyName];
}
public object Instance { get; private set; }
public PropertyDescriptor PropertyDescriptor { get; private set; }
public IContainer Container { get; private set; }
public void OnComponentChanged()
{
}
public bool OnComponentChanging()
{
return true;
}
public object GetService(Type serviceType)
{
return null;
}
}
So, let's consider a custom converter, as you see it can grab the existing object's property value using one line of code (note this code is compatible with standard existing ITypeDescriptorContext like the property grid one although in real life scenarios, you must check the context for nullity):
public class MyTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
// get existing value
object existingPropertyValue = context.PropertyDescriptor.GetValue(context.Instance);
// do something useful here
...
}
}
Now, if you have this custom object being modified:
public class MySampleObject
{
public MySampleObject()
{
MySampleProp = "hello world";
}
public string MySampleProp { get; set; }
}
You can call the converter like this:
MyTypeConverter tc = new MyTypeConverter();
object newValue = tc.ConvertFrom(new MyContext(new MySampleObject(), "MySampleProp"), null, "whatever");