Search code examples
wpfconverterscode-behind

Dynamically select built-in converter based on type in code-behind


I have a value coming in as a string, and I need to convert into a type. Now, XAML uses converters built-in to do this.

Is there any way to determine which type of converter to use solely on the type of the destination property?

I tried using the type converter, but of course it fails to convert from string to margin, because it's not sophisticated to know it needs to use a markup extension.

Code so far:

ResourceKey key = null;
if ((key = (value as ResourceKey)) != null)
{
   var descriptor = DependencyPropertyDescriptor.FromName(_PD.Name, _TargetEditor.TargetObject.GetType(), _TargetEditor.TargetObject.GetType());
                    ((FrameworkElement)_TargetEditor.TargetObject).SetResourceReference(descriptor.DependencyProperty, key);
   return;
}

if ((value is String) && (_PD.PropertyType != typeof(String)))
{
   this._PD.SetValue(_TargetEditor.TargetObject, Convert.ChangeType(value, _PD.PropertyType));
}
else
{
   this._PD.SetValue(_TargetEditor.TargetObject, value);
}

Solution

  • Get the type converter from the type converter attribute.

    AttributeCollection attributes = TypeDescriptor.GetAttributes(_PD.PropertyType);
    TypeConverterAttribute converterAttribute = (TypeConverterAttribute)attributes[typeof(TypeConverterAttribute)];
    if (converterAttribute != null)
    {
       Type converterType = Type.GetType(converterAttribute.ConverterTypeName);
       {
          _TypeConverter = (TypeConverter)Activator.CreateInstance(converterType);
       }
    }
    

    Then use the type converter if it exists.