1 //----------------------------------------------------------------
2 // Copyright (c) Microsoft Corporation. All rights reserved.
3 //----------------------------------------------------------------
5 namespace System.Activities.Presentation.Internal.PropertyEditing.Editors
7 using System.Windows.Data;
8 using System.Globalization;
9 using System.Collections.Generic;
11 using System.Collections;
12 sealed class FlagStringConverter : IValueConverter
14 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
18 return value.ToString();
26 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
28 Type flagType = parameter as Type;
29 Fx.Assert(flagType != null && flagType.IsEnum, "TargetType should be enum");
30 Fx.Assert(Attribute.IsDefined(flagType, typeof(FlagsAttribute)), "FlagType should have flags attribute");
34 return Enum.ToObject(flagType, 0);
37 string str = (value as string).ToUpperInvariant();
39 if (str.Equals(string.Empty) || str.Equals("0"))
41 return Enum.ToObject(flagType, 0);
44 Dictionary<string, object> flagDictionary = GenerateFlagDictionary(flagType);
45 int flagsIntValue = 0;
46 string[] names = str.Split(',');
47 foreach (string name in names)
49 string flagName = name.Trim();
50 if (flagDictionary.ContainsKey(flagName))
52 flagsIntValue |= (int)flagDictionary[flagName];
53 flagDictionary.Remove(flagName);
57 throw FxTrace.Exception.AsError(new ArgumentException(string.Format(CultureInfo.CurrentUICulture, SR.InvalidFlagName, value, flagType.Name)));
60 return Enum.ToObject(flagType, flagsIntValue);
63 static Dictionary<string, object> GenerateFlagDictionary(Type flagType)
65 Dictionary<string, object> flagDictionary = new Dictionary<string, object>();
66 string[] flagNames = flagType.GetEnumNames();
67 Array flagValues = flagType.GetEnumValues();
68 for (int i = 0; i < flagNames.Length; i++)
70 flagDictionary.Add(flagNames[i].ToUpperInvariant(), flagValues.GetValue(i));
72 return flagDictionary;