コード例 #1
0
        public static object EnumToObject(PropertyGridProperty property, object value)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            if (value != null && property.PropertyType.IsEnum)
            {
                return(Extensions.EnumToObject(property.PropertyType, value));
            }

            if (value != null && value.GetType().IsEnum)
            {
                return(Extensions.EnumToObject(value.GetType(), value));
            }

            if (property.PropertyType != typeof(string))
            {
                return(ConversionService.ChangeType(value, property.PropertyType));
            }

            var options = PropertyGridOptionsAttribute.FromProperty(property);

            if (options == null)
            {
                return(ConversionService.ChangeType(value, property.PropertyType));
            }

            return(EnumToObject(options, property.PropertyType, value));
        }
コード例 #2
0
        /// <summary>
        /// Gets the default value for a given property.
        /// </summary>
        /// <param name="propertyName">The property name. May not be null.</param>
        /// <returns>The default value. May be null.</returns>
        protected virtual object GetDefaultValue(string propertyName)
        {
            if (propertyName == null)
            {
                throw new ArgumentNullException("propertyName");
            }

            PropertyInfo pi = GetType().GetProperty(propertyName);

            if (pi == null)
            {
                if (ThrowOnInvalidProperty)
                {
                    throw new InvalidOperationException(SR.GetString("invalidPropertyName", GetType().FullName, propertyName));
                }

                return(null);
            }

            object defaultValue       = pi.PropertyType.IsValueType ? Activator.CreateInstance(pi.PropertyType) : null;
            DefaultValueAttribute att = Attribute.GetCustomAttribute(pi, typeof(DefaultValueAttribute), true) as DefaultValueAttribute;

            if (att != null)
            {
                return(ConversionService.ChangeType(att.Value, defaultValue));
            }

            return(defaultValue);
        }
コード例 #3
0
        protected virtual T GetProperty <T>([CallerMemberName] string name = null)
        {
            T      defaultValue;
            object obj;

            if (_defaultValues.TryGetValue(name, out obj))
            {
                defaultValue = ConversionService.ChangeType <T>(obj);
            }
            else
            {
                // runtime methodbase has no custom atts
                DefaultValueAttribute att = null;

                PropertyInfo pi = GetType().GetProperty(name);
                if (pi != null)
                {
                    att = Attribute.GetCustomAttribute(pi, typeof(DefaultValueAttribute), true) as DefaultValueAttribute;
                }

                defaultValue = att != null?ConversionService.ChangeType(att.Value, default(T)) : default(T);

                _defaultValues[name] = defaultValue;
            }

            return(GetProperty(defaultValue, name));
        }
コード例 #4
0
        protected virtual void OnGuidCommandExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            var tb = e.OriginalSource as TextBox;

            if (tb != null)
            {
                if (NewGuidCommand.Equals(e.Command))
                {
                    tb.Text = Guid.NewGuid().ToString(NormalizeGuidParameter(e.Parameter));
                    return;
                }

                if (EmptyGuidCommand.Equals(e.Command))
                {
                    tb.Text = Guid.Empty.ToString(NormalizeGuidParameter(e.Parameter));
                    return;
                }

                if (IncrementGuidCommand.Equals(e.Command))
                {
                    Guid   g     = ConversionService.ChangeType(tb.Text.Trim(), Guid.Empty);
                    byte[] bytes = g.ToByteArray();
                    bytes[15]++;
                    tb.Text = new Guid(bytes).ToString(NormalizeGuidParameter(e.Parameter));
                    return;
                }
            }
        }
コード例 #5
0
        protected virtual bool TryChangeType(object value, Type type, IFormatProvider provider, out object changedValue)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            return(ConversionService.TryChangeType(value, type, provider, out changedValue));
        }
コード例 #6
0
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Type parameterType = GetParameterAsType(parameter);

            if (parameterType != null)
            {
                value = ConversionService.ChangeType(value, parameterType, null, culture);
            }

            object convertedValue = targetType == null ? value : ConversionService.ChangeType(value, targetType, null, culture);

            return(convertedValue);
        }
コード例 #7
0
        /// <summary>
        /// Gets a property value.
        /// </summary>
        /// <typeparam name="T">The property type.</typeparam>
        /// <param name="defaultValue">The default value.</param>
        /// <param name="name">The property name. May not be null.</param>
        /// <returns></returns>
        protected virtual T GetProperty <T>(T defaultValue, [CallerMemberName] string name = null)
        {
            if (name == null)
            {
                throw new ArgumentNullException("name");
            }

            object obj;

            if (!Properties.TryGetValue(name, out obj))
            {
                return(defaultValue);
            }

            return(ConversionService.ChangeType(obj, defaultValue));
        }
コード例 #8
0
        private string ValueToString(IFormatProvider provider)
        {
            if (Value == null)
            {
                return(null);
            }

            string v = Value as string;

            if (v == null)
            {
                v = ConversionService.ChangeType <string>(Value, null, provider);
                if (v == null)
                {
                    v = string.Format(provider, "{0}", Value);
                }
            }
            return(v);
        }
コード例 #9
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (targetType == typeof(string) && !(value is string) && value is IEnumerable)
     {
         var sb         = new StringBuilder();
         var enumerable = value as IEnumerable;
         if (enumerable != null)
         {
             foreach (object obj in enumerable)
             {
                 if (sb.Length > 0)
                 {
                     sb.Append(Separator);
                 }
                 sb.AppendFormat(Format, obj);
             }
         }
         return(sb.ToString());
     }
     return(ConversionService.ChangeType(value, targetType));
 }
コード例 #10
0
        /// <summary>
        /// Converts a value.
        /// </summary>
        /// <param name="value">The value produced by the binding source.</param>
        /// <param name="targetType">The type of the binding target property.</param>
        /// <param name="parameter">The converter parameter to use.</param>
        /// <param name="culture">The culture to use in the converter.</param>
        /// <returns>
        /// A converted value. If the method returns null, the valid null value is used.
        /// </returns>
        public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (_cases.Count == 0)
            {
                return(ConversionService.ChangeType(value, targetType, culture));
            }

            foreach (UniversalConverterCase c in _cases)
            {
                if (c.Matches(value, parameter, culture))
                {
                    if ((c.Options & UniversalConverterOptions.ConvertedValueIsConverterParameter) == UniversalConverterOptions.ConvertedValueIsConverterParameter)
                    {
                        return(ConversionService.ChangeType(parameter, targetType, culture));
                    }

                    return(ConversionService.ChangeType(c.ConvertedValue, targetType, null, culture));
                }
            }

            return(ConversionService.ChangeType(DefaultValue, targetType, null, culture));
        }
コード例 #11
0
        private string ValueToCompareToString(IFormatProvider provider, bool forceConvert)
        {
            if (ValueToCompare == null)
            {
                return(null);
            }

            string v = ValueToCompare as string;

            if (v == null)
            {
                if (forceConvert || (Options & UniversalConverterOptions.Convert) == UniversalConverterOptions.Convert)
                {
                    v = ConversionService.ChangeType <string>(ValueToCompare, null, provider);
                    if (v == null)
                    {
                        v = string.Format(provider, "{0}", ValueToCompare);
                    }
                }
            }

            if ((Options & UniversalConverterOptions.Trim) == UniversalConverterOptions.Trim)
            {
                if (v != null)
                {
                    v = v.Trim();
                }
            }

            if ((Options & UniversalConverterOptions.Nullify) == UniversalConverterOptions.Nullify)
            {
                if (v != null && v.Length == 0)
                {
                    v = null;
                }
            }
            return(v);
        }
コード例 #12
0
        /// <summary>
        /// Determine if the input values matches, depending on the input operator and options.
        /// </summary>
        /// <param name="provider">An IFormatProvider interface implementation that supplies culture-specific formatting information.</param>
        /// <returns>true if the values matches; false otherwise.</returns>
        public virtual bool Matches(IFormatProvider provider)
        {
            bool   ret = false;
            string v;
            string vtc;
            UniversalConverterInput clone;

            switch (Operator)
            {
            case UniversalConverterOperator.Equal:
                if (Value == null)
                {
                    if (ValueToCompare == null)
                    {
                        ret = true;
                        break;
                    }

                    // use string comparison (to compare "" to null or similar)
                    v   = ValueToCompareToString(provider, false);
                    ret = v == null;
                    break;     // false
                }

                if (Value.Equals(ValueToCompare))
                {
                    ret = true;
                    break;
                }

                v = Value as string;
                if (v != null)
                {
                    vtc = ValueToCompareToString(provider, true);
                    ret = string.Compare(v, vtc, StringComparison) == 0;
                    break;
                }

                if ((Options & UniversalConverterOptions.Convert) == UniversalConverterOptions.Convert)
                {
                    object cvalue;
                    if (ConversionService.TryChangeType(ValueToCompare, Value.GetType(), provider, out cvalue))
                    {
                        if (Value.Equals(cvalue))
                        {
                            ret = true;
                            break;
                        }

                        if (Value.GetType() == typeof(string))
                        {
                            string sv = (string)cvalue;
                            if ((Options & UniversalConverterOptions.Trim) == UniversalConverterOptions.Trim)
                            {
                                sv = sv.Trim();
                            }

                            if ((Options & UniversalConverterOptions.Nullify) == UniversalConverterOptions.Nullify)
                            {
                                if (sv.Length == 0)
                                {
                                    sv = null;
                                }
                            }

                            if (Value.Equals(sv))
                            {
                                ret = true;
                                break;
                            }
                        }
                    }
                }
                break;

            case UniversalConverterOperator.NotEqual:
                clone          = Clone();
                clone.Operator = UniversalConverterOperator.Equal;
                ret            = clone.Matches(provider);
                break;

            case UniversalConverterOperator.Contains:
                v = ValueToString(provider);
                if (v == null)
                {
                    break;
                }

                vtc = ValueToCompareToString(provider, true);
                if (vtc == null)
                {
                    break;
                }

                ret = v.IndexOf(vtc, StringComparison) >= 0;
                break;

            case UniversalConverterOperator.StartsWith:
                v = ValueToString(provider);
                if (v == null)
                {
                    break;
                }

                vtc = ValueToCompareToString(provider, true);
                if (vtc == null)
                {
                    break;
                }

                ret = v.StartsWith(vtc, StringComparison);
                break;

            case UniversalConverterOperator.EndsWith:
                v = ValueToString(provider);
                if (v == null)
                {
                    break;
                }

                vtc = ValueToCompareToString(provider, true);
                if (vtc == null)
                {
                    break;
                }

                ret = v.EndsWith(vtc, StringComparison);
                break;

            case UniversalConverterOperator.LesserThanOrEqual:
            case UniversalConverterOperator.LesserThan:
            case UniversalConverterOperator.GreaterThanOrEqual:
            case UniversalConverterOperator.GreaterThan:
                var cv = Value as IComparable;
                if (cv == null || ValueToCompare == null)
                {
                    break;
                }

                IComparable cvtc;
                if (!Value.GetType().IsAssignableFrom(ValueToCompare.GetType()))
                {
                    cvtc = ConversionService.ChangeType(ValueToCompare, Value.GetType(), provider) as IComparable;
                }
                else
                {
                    cvtc = ValueToCompare as IComparable;
                }
                if (cvtc == null)
                {
                    break;
                }

                int comparison;
                v = Value as string;
                if (StringComparison != StringComparison.CurrentCulture)     // not the default? use the special string comparer
                {
                    vtc        = ValueToCompareToString(provider, true);
                    comparison = string.Compare(v, vtc, StringComparison);
                }
                else
                {
                    comparison = cv.CompareTo(cvtc);
                }

                if (comparison == 0)
                {
                    ret = Operator == UniversalConverterOperator.GreaterThanOrEqual || Operator == UniversalConverterOperator.LesserThanOrEqual;
                    break;
                }

                if (comparison < 0)
                {
                    ret = Operator == UniversalConverterOperator.LesserThan || Operator == UniversalConverterOperator.LesserThanOrEqual;
                    break;
                }

                ret = Operator == UniversalConverterOperator.GreaterThan || Operator == UniversalConverterOperator.GreaterThanOrEqual;
                break;

            case UniversalConverterOperator.Between:
                clone = Clone();
                clone.ValueToCompare = MinimumValue;
                clone.Operator       = UniversalConverterOperator.GreaterThanOrEqual;
                if (!clone.Matches(provider))
                {
                    break;
                }

                clone = Clone();
                clone.ValueToCompare = MaximumValue;
                clone.Operator       = UniversalConverterOperator.LesserThan;
                ret = clone.Matches(provider);
                break;

            case UniversalConverterOperator.IsType:
            case UniversalConverterOperator.IsOfType:
                Type tvtc = ValueToCompareToType(provider);
                if (tvtc == null)
                {
                    break;
                }

                if (Value == null)
                {
                    if (tvtc.IsValueType)
                    {
                        break;
                    }

                    ret = (Options & UniversalConverterOptions.NullMatchesType) == UniversalConverterOptions.NullMatchesType;
                    break;
                }

                if (Operator == UniversalConverterOperator.IsType)
                {
                    ret = Value.GetType() == tvtc;
                }
                else
                {
                    ret = tvtc.IsAssignableFrom(Value.GetType());
                }
                break;
            }

            return(Reverse ? !ret : ret);
        }
コード例 #13
0
 /// <summary>
 /// Converts a value.
 /// </summary>
 /// <param name="value">The value that is produced by the binding target.</param>
 /// <param name="targetType">The type to convert to.</param>
 /// <param name="parameter">The converter parameter to use.</param>
 /// <param name="culture">The culture to use in the converter.</param>
 /// <returns>
 /// A converted value. If the method returns null, the valid null value is used.
 /// </returns>
 public virtual object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(ConversionService.ChangeType(parameter, targetType, null, culture));
 }
コード例 #14
0
        public virtual IEnumerable BuildItems(PropertyGridProperty property, Type targetType, object parameter, CultureInfo culture)
        {
            if (property == null)
            {
                throw new ArgumentNullException("property");
            }

            Type enumType;
            bool nullable;
            bool isEnumOrNullableEnum = PropertyGridProperty.IsEnumOrNullableEnum(property.PropertyType, out enumType, out nullable);

            PropertyGridItem zero = null;
            var att   = PropertyGridOptionsAttribute.FromProperty(property);
            var items = new ObservableCollection <PropertyGridItem>();

            if (isEnumOrNullableEnum)
            {
                if (nullable)
                {
                    PropertyGridItem item = CreateItem();
                    item.Property = property;
                    item.Name     = null; // "<unset>";
                    item.Value    = null;
                    item.IsUnset  = true;
                    items.Add(item);
                }

                string[] names  = Enum.GetNames(enumType);
                Array    values = Enum.GetValues(enumType);
                if (Extensions.IsFlagsEnum(enumType))
                {
                    ulong uvalue = EnumToUInt64(property, property.Value);

                    for (int i = 0; i < names.Length; i++)
                    {
                        string name      = names[i];
                        ulong  nameValue = EnumToUInt64(property, values.GetValue(i));
                        string displayName;
                        if (!ShowEnumField(property, enumType, names[i], out displayName))
                        {
                            continue;
                        }

                        PropertyGridItem item = CreateItem();
                        item.Property = property;
                        item.Name     = displayName;
                        item.Value    = nameValue;
                        item.IsZero   = nameValue == 0;
                        bool isChecked = true;

                        if (nameValue == 0)
                        {
                            zero = item;
                        }

                        // determine if this name is in fact a combination of other names
                        ulong bitsCount = (ulong)Extensions.GetEnumMaxPower(enumType) - 1; // skip first
                        ulong b         = 1;
                        for (ulong bit = 1; bit < bitsCount; bit++)                        // signed, skip highest bit
                        {
                            string bitName = Enum.GetName(enumType, b);
                            if (bitName != null && name != bitName && (nameValue & b) != 0)
                            {
                                if ((uvalue & b) == 0)
                                {
                                    isChecked = false;
                                }
                            }
                            b *= 2;
                        }

                        isChecked      = (uvalue & nameValue) != 0;
                        item.IsChecked = isChecked;
                        items.Add(item);
                    }

                    // determine if the lisbox is empty, which we don't want anyway
                    if (items.Count == 0)
                    {
                        PropertyGridItem item = CreateItem();
                        item.Property = property;
                        item.Name     = DefaultZeroName;
                        item.Value    = 0;
                        item.IsZero   = true;
                        items.Add(item);
                    }

                    if (uvalue == 0 && zero != null)
                    {
                        zero.IsChecked = true;
                    }
                }
                else
                {
                    for (int i = 0; i < names.Length; i++)
                    {
                        string displayName;
                        if (!ShowEnumField(property, enumType, names[i], out displayName))
                        {
                            continue;
                        }

                        PropertyGridItem item = CreateItem();
                        item.Property = property;
                        item.Name     = displayName;
                        item.Value    = values.GetValue(i);
                        item.IsZero   = i == 0; // first one is default
                        items.Add(item);
                    }
                }
            }
            else
            {
                if (att != null && att.IsEnum)
                {
                    bool manualFlags = false;
                    // either EnumList or EnumValues can be null but not both
                    // if not null, length must be the same
                    if (att.EnumNames == null || att.EnumNames.Length == 0)
                    {
                        if (att.EnumValues == null || att.EnumValues.Length == 0)
                        {
                            return(items);
                        }

                        att.EnumNames = new string[att.EnumValues.Length];
                        for (int i = 0; i < att.EnumValues.Length; i++)
                        {
                            att.EnumNames[i] = string.Format("{0}", att.EnumValues[i]);
                        }
                    }
                    else
                    {
                        if (att.EnumValues == null || att.EnumValues.Length != att.EnumNames.Length)
                        {
                            att.EnumValues = new object[att.EnumNames.Length];
                            if (att.IsFlagsEnum)
                            {
                                ulong current = 1; // don't use zero when nothing is specified in flags mode
                                manualFlags = true;
                                for (int i = 0; i < att.EnumNames.Length; i++)
                                {
                                    att.EnumValues[i] = current;
                                    current          *= 2;
                                }
                            }
                            else
                            {
                                for (int i = 0; i < att.EnumNames.Length; i++)
                                {
                                    att.EnumValues[i] = string.Format("{0}", att.EnumNames[i]);
                                }
                            }
                        }
                    }

                    // items value must of a compatible type with property.Value
                    Func <object, object> valueConverter = (v) =>
                    {
                        Type propType = property.Value != null?property.Value.GetType() : property.PropertyType;

                        if (v == null)
                        {
                            if (!propType.IsValueType)
                            {
                                return(null);
                            }

                            return(Activator.CreateInstance(propType));
                        }

                        Type vType = v.GetType();
                        if (propType.IsAssignableFrom(vType))
                        {
                            return(v);
                        }

                        return(ConversionService.ChangeType(v, propType));
                    };

                    if (att.IsFlagsEnum)
                    {
                        ulong uvalue = EnumToUInt64(property, property.Value);

                        for (int i = 0; i < att.EnumNames.Length; i++)
                        {
                            ulong nameValue = EnumToUInt64(property, att.EnumValues[i]);

                            PropertyGridItem item = CreateItem();
                            item.Property = property;
                            item.Name     = att.EnumNames[i];
                            item.Value    = valueConverter(att.EnumValues[i]);
                            if (manualFlags)
                            {
                                item.IsZero = i == 0;
                            }
                            else
                            {
                                item.IsZero = nameValue == 0;
                            }
                            bool isChecked = true;

                            if (nameValue == 0)
                            {
                                zero = item;
                            }

                            // note: in this case, we don't support names as a combination of other names
                            ulong bitsCount = (ulong)GetEnumMaxPower(att) - 1; // skip first
                            ulong b         = 1;
                            for (ulong bit = 1; bit < bitsCount; bit++)        // signed, skip highest bit
                            {
                                if ((uvalue & b) == 0)
                                {
                                    isChecked = false;
                                }
                                b *= 2;
                            }

                            isChecked      = (uvalue & nameValue) != 0;
                            item.IsChecked = isChecked;
                            items.Add(item);
                        }

                        // determine if the list is empty, which we don't want anyway
                        if (items.Count == 0)
                        {
                            PropertyGridItem item = CreateItem();
                            item.Property = property;
                            item.Name     = DefaultZeroName;
                            item.Value    = valueConverter(0);
                            item.IsZero   = true;
                            items.Add(item);
                        }

                        if (uvalue == 0 && zero != null)
                        {
                            zero.IsChecked = true;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < att.EnumNames.Length; i++)
                        {
                            PropertyGridItem item = CreateItem();
                            item.Property = property;
                            item.Name     = att.EnumNames[i];
                            item.Value    = valueConverter(att.EnumValues[i]);
                            item.IsZero   = i == 0; // first one is default
                            items.Add(item);
                        }
                    }
                }
            }

            var ctx = new Dictionary <string, object>();

            ctx["items"] = items;
            property.OnEvent(this, ActivatorService.CreateInstance <PropertyGridEventArgs>(property, ctx));
            return(items);
        }
コード例 #15
0
        public static object EnumToObject(PropertyGridOptionsAttribute options, Type propertyType, object value)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            if (propertyType == null)
            {
                throw new ArgumentNullException("propertyType");
            }

            if (value != null && propertyType.IsEnum)
            {
                return(Extensions.EnumToObject(propertyType, value));
            }

            if (value != null && value.GetType().IsEnum)
            {
                return(Extensions.EnumToObject(value.GetType(), value));
            }

            if (propertyType != typeof(string))
            {
                return(ConversionService.ChangeType(value, propertyType));
            }

            if (options == null || options.EnumNames == null || options.EnumValues == null || options.EnumValues.Length != options.EnumNames.Length)
            {
                return(ConversionService.ChangeType(value, propertyType));
            }

            if (BaseConverter.IsNullOrEmptyString(value))
            {
                return(string.Empty);
            }

            var    sb     = new StringBuilder();
            string svalue = string.Format("{0}", value);
            ulong  ul;

            if (!ulong.TryParse(svalue, out ul))
            {
                var enums = ParseEnum(svalue);
                if (enums.Count == 0)
                {
                    return(string.Empty);
                }

                var enumValues = options.EnumValues.Select(v => string.Format("{0}", v)).ToArray();
                foreach (string enumValue in enums)
                {
                    int index = IndexOf(enumValues, enumValue);
                    if (index < 0)
                    {
                        index = IndexOf(options.EnumNames, enumValue);
                    }

                    if (index >= 0)
                    {
                        if (sb.Length > 0 && options.EnumSeparator != null)
                        {
                            sb.Append(options.EnumSeparator);
                        }
                        sb.Append(options.EnumNames[index]);
                    }
                }
            }
            else // a string
            {
                ulong bitsCount = (ulong)GetEnumMaxPower(options) - 1; // skip first
                ulong b         = 1;
                for (ulong bit = 1; bit < bitsCount; bit++) // signed, skip highest bit
                {
                    if ((ul & b) != 0)
                    {
                        int index = IndexOf(options.EnumValues, b);
                        if (index >= 0)
                        {
                            if (sb.Length > 0 && options.EnumSeparator != null)
                            {
                                sb.Append(options.EnumSeparator);
                            }
                            sb.Append(options.EnumNames[index]);
                        }
                    }
                    b *= 2;
                }
            }

            string s = sb.ToString();

            if (s.Length == 0)
            {
                int index = IndexOf(options.EnumValues, 0);
                if (index >= 0)
                {
                    s = options.EnumNames[index];
                }
            }

            return(s);
        }
コード例 #16
0
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object convertedValue = targetType == null ? value : ConversionService.ChangeType(value, targetType, null, culture);

            return(convertedValue);
        }