Merge pull request #2903 from krytarowski/netbsd-support-4
[mono.git] / mcs / class / referencesource / System.Activities.Presentation / System.Activities.Presentation / System / Activities / Presentation / View / TypeToStringValueConverter.cs
1 //----------------------------------------------------------------
2 // Copyright (c) Microsoft Corporation.  All rights reserved.
3 //----------------------------------------------------------------
4
5 namespace System.Activities.Presentation.View
6 {
7     using System.Diagnostics;
8     using System.Globalization;
9     using System.Windows.Data;
10     using System.Runtime;
11
12     class TypeToStringValueConverter : IValueConverter
13     {
14         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
15         {
16             Fx.Assert(targetType.Equals(typeof(string)), "TypeToStringValueConverter cannot convert a type to type " + targetType.FullName);
17             string target = null;
18             if (value != null)
19             {
20                 Fx.Assert(value is Type, string.Format(CultureInfo.InvariantCulture, "TypeToStringValueConverter cannot convert from type {0} to string", value.GetType().FullName));
21                 Type editedType = (Type)value;
22                 //handle primitive types
23                 if (editedType.IsPrimitive || editedType.IsValueType ||
24                     editedType == typeof(string) || editedType == typeof(object))
25                 {
26                     target = editedType.Name;
27                 }
28                     //and other ones
29                 else
30                 {
31                     target = editedType.FullName;
32                 }
33             }
34             return target;
35         }
36
37         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
38         {
39             Fx.Assert(targetType.Equals(typeof(Type)), "TypeToStringValueConverter cannot convert string back to type " + targetType.FullName);
40             Type target = null;
41             string stringValue = value as string;
42             if (!string.IsNullOrEmpty(stringValue))
43             {
44                 // try to get the type from the type name
45                 target = Type.GetType(stringValue, false, true);
46                 //handle primitive types
47                 if (null == target)
48                 {
49                     stringValue = string.Format(CultureInfo.InvariantCulture, "System.{0}", stringValue);
50                     target = Type.GetType(stringValue, false, true);
51                 }
52                 if (null == target)
53                 {
54                     return Binding.DoNothing;
55                 }
56             }
57             return target;
58         }
59     }
60 }