private object CastResult(object result, Type targetType)
{
if (result == null || result == DependencyProperty.UnsetValue || result == System.Windows.Data.Binding.DoNothing || targetType == null || targetType == typeof(object))
{
return(result);
}
if (targetType == typeof(string))
{
return(result.ToString());
}
Func <object, object> cast;
if (!castFunctions.TryGetValue(targetType, out cast))
{
ParameterExpression par = Expression.Parameter(typeof(object));
cast = Expression.Lambda <Func <object, object> >(Expression.Convert(Expression.Dynamic(Binder.Convert(CSharpBinderFlags.ConvertExplicit, targetType, typeof(object)), targetType, par), typeof(object)), par).Compile();
castFunctions.TryAdd(targetType, cast);
}
if (cast != null)
{
try
{
result = cast(result);
}
catch
{
castFunctions[targetType] = null;
}
}
return(result);
}