static string GetEnumName(FieldInfo field, Enum value, IValueConverter nameConverter, bool splitNames) {
            if(nameConverter != null)
                return nameConverter.Convert(value, typeof(string), null, CultureInfo.CurrentCulture) as string;
            string name = DataAnnotationsAttributeHelper.GetFieldDisplayName(field) ??
#if !SILVERLIGHT
 TypeDescriptor.GetConverter(value.GetType()).ConvertTo(value, typeof(string)) as string
#else
                value.ToString()
#endif
;
            if(splitNames)
                return SplitStringHelper.SplitPascalCaseString(name);
            return name;
        }
 public void ConvertWithNullParameter_ShouldThrowArgumentNullException(IValueConverter converter)
 {
     try
     {
         result = converter.Convert(null, null, null, "");
         Assert.Fail("An exception should have been thrown");
     }
     catch (ArgumentNullException exception)
     {
         StringAssert.Contains(exception.Message, "");
     }
     catch(Exception e)
     {
         Assert.Fail("Wrong exception  has been thrown");
     }
 }
Esempio n. 3
0
            private void UpdateTarget()
            {
                try {
                    var sourceValue = sourceBindingProperty.GetValue(sourceDataContext);
                    if (sourceValue == null)
                    {
                        return;
                    }

                    var finalValue = valueConverter?.Convert(sourceValue) ?? sourceValue;

                    var targetProperty = Target.GetType().GetProperty(TargetPropertyName);
                    targetProperty.SetValue(Target, finalValue);
                } catch (Exception ex) {
                    MessageBox.ErrorQuery("Binding Error", $"Binding failed: {ex}.", "Ok");
                }
            }
Esempio n. 4
0
        /// <summary>
        /// Sets the value of the property or field with the specified <paramref name="name"/> when running on one of the specified <see cref="MobileTarget"/>s.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="name">The name of the property or field whose value is to be set.</param>
        /// <param name="value">The value to set to the property or field.</param>
        /// <param name="index">Optional index values for indexed properties.  This value should be <c>null</c> for non-indexed properties.</param>
        /// <param name="converter">An optional converter to use on the value prior to setting the property or field.</param>
        /// <param name="targets">The targets on which the code must be running for the value to be set.</param>
        public static void SetValue(this IPairable obj, string name, object value, object[] index, IValueConverter converter, MobileTarget targets)
        {
            if (obj == null || !targets.HasFlag(iApp.Factory.Target))
            {
                return;
            }

            var type = obj.GetType();

            try
            {
                var property = Device.Reflector.GetProperty(type, name);
                if (property != null)
                {
                    if (converter != null)
                    {
                        value = converter.Convert(value, property.PropertyType, null);
                    }
                    else
                    {
                        value = Binding.GetConvertedValue(value, property.PropertyType);
                    }
                    property.SetValue(obj, value, index);
                    return;
                }

                var field = Device.Reflector.GetField(type, name);
                if (field != null)
                {
                    if (converter != null)
                    {
                        value = converter.Convert(value, field.FieldType, null);
                    }
                    else
                    {
                        value = Binding.GetConvertedValue(value, field.FieldType);
                    }
                    field.SetValue(obj, value);
                    return;
                }

                if (obj != null && obj.Pair != null)
                {
                    type     = obj.Pair.GetType();
                    property = Device.Reflector.GetProperty(type, name);
                    if (property != null)
                    {
                        if (converter != null)
                        {
                            value = converter.Convert(value, property.PropertyType, null);
                        }
                        else
                        {
                            value = Binding.GetConvertedValue(value, property.PropertyType);
                        }
                        property.SetValue(obj.Pair, value, index);
                        return;
                    }

                    field = Device.Reflector.GetField(type, name);
                    if (field != null)
                    {
                        if (converter != null)
                        {
                            value = converter.Convert(value, field.FieldType, null);
                        }
                        else
                        {
                            value = Binding.GetConvertedValue(value, field.FieldType);
                        }
                        field.SetValue(obj.Pair, value);
                    }
                }
            }
            catch (Exception e)
            {
                iApp.Log.Warn("Unable to set value of member on {0}.", e, obj.ToString());
            }
        }
        private object ConvertHelper(IValueConverter converter, object value, Type targetType, object parameter, CultureInfo culture)
        {
            // use the StringFormat (if appropriate) in preference to the default converter
            string stringFormat = EffectiveStringFormat;
            Invariant.Assert(converter != null || stringFormat != null);

            // PreSharp uses message numbers that the C# compiler doesn't know about.
            // Disable the C# complaints, per the PreSharp documentation.
            #pragma warning disable 1634, 1691

            // PreSharp complains about catching NullReference (and other) exceptions.
            // It doesn't recognize that IsCritical[Application]Exception() handles these correctly.
            #pragma warning disable 56500

            object convertedValue = null;
            try
            {
                if (stringFormat != null)
                {
                    convertedValue = String.Format(culture, stringFormat, value);
                }
                else
                {
                    convertedValue = converter.Convert(value, targetType, parameter, culture);
                }
            }

            // Catch all exceptions.  There is no app code on the stack,
            // so the exception isn't actionable by the app.
            // Yet we don't want to crash the app.
            catch (Exception ex)
            {
                // the DefaultValueConverter can end up calling BaseUriHelper.GetBaseUri()
                // which can raise SecurityException if the app does not have the right FileIO privileges
                if (CriticalExceptions.IsCriticalApplicationException(ex))
                    throw;

                if (TraceData.IsEnabled)
                {
                    string name = String.IsNullOrEmpty(stringFormat) ? converter.GetType().Name : "StringFormat";
                    TraceData.Trace(TraceLevel,
                            TraceData.BadConverterForTransfer(
                                name,
                                AvTrace.ToStringHelper(value),
                                AvTrace.TypeName(value)),
                            this, ex);
                }
                convertedValue = DependencyProperty.UnsetValue;
            }
            catch // non CLS compliant exception
            {
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceLevel,
                            TraceData.BadConverterForTransfer(
                                converter.GetType().Name,
                                AvTrace.ToStringHelper(value),
                                AvTrace.TypeName(value)),
                            this);
                }
                convertedValue = DependencyProperty.UnsetValue;
            }

            #pragma warning restore 56500
            #pragma warning restore 1634, 1691

            return convertedValue;
        }
Esempio n. 6
0
 protected override IPropertyValue ConvertFirstArgument(IEnumerable <CssToken> value)
 {
     return(_converter.Convert(value));
 }
Esempio n. 7
0
 /// <inheritdoc/>
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(_converter.Convert(value, targetType, parameter, culture));
 }
Esempio n. 8
0
 private T Convert <T>(IValueConverter converter, T value, T range)
 {
     return((T)converter.Convert(value, typeof(T), range, CultureInfo.CurrentCulture));
 }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var inverted = _invertBoolConverter.Convert(value, targetType, parameter, culture);

            return(_boolToVis.Convert(inverted, targetType, parameter, culture));
        }
Esempio n. 10
0
    protected T GetBoundValue <T>(IValueConverter converter)
    {
        object intermediate = converter.Convert(propertyInfo.GetValue(target, null));

        return((T)Convert.ChangeType(intermediate, typeof(T)));
    }
Esempio n. 11
0
 protected override object ConvertCore(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(_converter != null?_converter.Convert(ConvertOverride(value, targetType, parameter, culture), targetType, parameter, culture) : ConvertOverride(value, targetType, parameter, culture));
 }
 public void SetDateAsClipboardText(IValueConverter converter)
 {
     UiUtils.SetClipboardText((string)converter.Convert(MODEL.Message.Message.date, typeof(string), null, null));
 }
Esempio n. 13
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return((bool)_delegateConverter.Convert(value, targetType, parameter, culture) ? True : False);
 }
Esempio n. 14
0
        object IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
            {
                return(DependencyProperty.UnsetValue);
            }
            object[] unconvertedValues = (object[])value;
            object   converter         = Converter;

            object result = unconvertedValues;

            if (converter != null)
            {
                object converterParameter = ConverterParameter;
                SourceValuesErrors = null;
                try
                {
                    IMultiValueConverter multiConverter = converter as IMultiValueConverter;
                    if (multiConverter != null)
                    {
                        result = multiConverter.Convert(unconvertedValues, targetType, converterParameter, culture);
                    }
                    else
                    {
                        IValueConverter singleConverter = converter as IValueConverter;
                        if (singleConverter != null)
                        {
                            result = singleConverter.Convert(unconvertedValues[0], targetType, converterParameter, culture);
                        }
                    }
                }
                catch (Exception ex)
                {
                    SourceValuesErrors = new MultiBindingValidationError[] { new MultiBindingValidationError(ex) };
                    if (MultiBinding.ValidatesOnExceptions)
                    {
                        return(DependencyProperty.UnsetValue);
                    }
                    throw;
                }
            }


            if (result != DependencyProperty.UnsetValue)
            {
                String format = StringFormat;
                if (format != null)
                {
                    format = Regex.Replace(format, @"%(\d+)", "{$1}");
                    if (result is Object[])
                    {
                        result = String.Format(culture, format, (Object[])result);
                    }
                    else
                    {
                        result = String.Format(culture, format, result);
                    }
                }
            }
            return(result);
        }
Esempio n. 15
0
        public static void SetTargetProperty(object rawValue,
                                             object view, PropertyInfo targetProperty, IValueConverter converter, string converterParameter)
        {
            try
            {
                if (targetProperty == null)
                {
                    throw new ArgumentNullException(nameof(targetProperty));
                }

                if (view == null)
                {
                    throw new ArgumentNullException(nameof(view));
                }

                // Use the converter
                var sourcePropertyValue = converter == null
                    ? rawValue
                    : converter.Convert(rawValue,
                                        targetProperty.PropertyType,
                                        converterParameter,
                                        CultureInfo.CurrentCulture);

                /* Need some implicit type coercion here.
                 * Perhaps pull that in from Calciums property binding system. */
                var property = targetProperty;
                if (property.PropertyType == typeof(string) &&
                    !(sourcePropertyValue is string) &&
                    sourcePropertyValue != null)
                {
                    sourcePropertyValue = sourcePropertyValue.ToString();
                }
                else if (property.PropertyType == typeof(Android.Views.ViewStates))
                {
                    if (!(sourcePropertyValue is Android.Views.ViewStates))
                    {
                        // Implicit visibility converter
                        bool?shouldBeVisible = null;
                        if (sourcePropertyValue is bool boolean)
                        {
                            shouldBeVisible = boolean;
                        }
                        else
                        {
                            // If not null, visible
                            shouldBeVisible = sourcePropertyValue != null;
                        }

                        if (shouldBeVisible != null)
                        {
                            sourcePropertyValue = shouldBeVisible.Value ? Android.Views.ViewStates.Visible : Android.Views.ViewStates.Gone;
                        }
                    }
                }

                if (targetProperty.DeclaringType == typeof(TextViewStrikethroughWrapper))
                {
                    var wrapper = new TextViewStrikethroughWrapper(view as TextView);
                    targetProperty.SetValue(wrapper, sourcePropertyValue);
                }
                else if (view is View androidView && targetProperty.Name == nameof(androidView.BackgroundTintList) && sourcePropertyValue is ColorStateList colorStateList)
                {
                    // Use ViewCompat since this property didn't exist till API 21
                    try
                    {
                        ViewCompat.SetBackgroundTintList(androidView, colorStateList);
                    }
                    catch (Java.Lang.RuntimeException)
                    {
                        // This theoretically shouldn't ever fail, yet it seems to fail sometimes due to a null reference exception
                        // which makes no sense. So I'll just catch it.
                    }
                }
                else if (targetProperty.Name == nameof(View.HasFocus))
                {
                    // Don't do anything, these are only one-way where the viewmodel updates but the view never updates
                }
                else
                {
                    targetProperty.SetValue(view, sourcePropertyValue);
                }
            }
        public TighteningErrorStatus2 Convert(string value)
        {
            var bytes = _byteArrayConverter.Convert(value);

            return(ConvertFromBytes(bytes));
        }
Esempio n. 17
0
        private object DoConversion(object value, Type targetType, object parameter, Func <object, object[], object, object> func, bool convertingBack, CultureInfo culture)
        {
            if (convertingBack)
            {
                if (_chainedConverter != null)
                {
                    try { value = _chainedConverter.ConvertBack(value, targetType, parameter, culture); }
                    catch (Exception e)
                    {
                        EquationTokenizer.ThrowQuickConverterEvent(new ChainedConverterExceptionEventArgs(ConvertExpression, value, targetType, parameter, culture, true, _chainedConverter, this, e));
                        return(DependencyProperty.UnsetValue);
                    }

                    if (value == DependencyProperty.UnsetValue || value == System.Windows.Data.Binding.DoNothing)
                    {
                        return(value);
                    }
                }

                if (ValueType != null && !ValueType.IsInstanceOfType(value))
                {
                    return(System.Windows.Data.Binding.DoNothing);
                }
            }
            else
            {
                if (value == DependencyProperty.UnsetValue || _namedObjectType.IsInstanceOfType(value) || (PType != null && !PType.IsInstanceOfType(value)))
                {
                    return(DependencyProperty.UnsetValue);
                }
            }

            object result = value;

            if (func != null)
            {
                try { result = func(result, _values, parameter); }
                catch (Exception e)
                {
                    LastException = e;
                    ++ExceptionCount;
                    if (Debugger.IsAttached)
                    {
                        Console.WriteLine("QuickMultiConverter Exception (\"" + (convertingBack ? ConvertBackExpression : ConvertExpression) + "\") - " + e.Message + (e.InnerException != null ? " (Inner - " + e.InnerException.Message + ")" : ""));
                    }
                    if (convertingBack)
                    {
                        EquationTokenizer.ThrowQuickConverterEvent(new RuntimeSingleConvertExceptionEventArgs(ConvertBackExpression, ConvertBackExpressionDebugView, null, value, _values, parameter, this, e));
                    }
                    else
                    {
                        EquationTokenizer.ThrowQuickConverterEvent(new RuntimeSingleConvertExceptionEventArgs(ConvertExpression, ConvertExpressionDebugView, value, null, _values, parameter, this, e));
                    }
                    return(DependencyProperty.UnsetValue);
                }
                finally
                {
                    var dataContainers = convertingBack ? _fromDataContainers : _toDataContainers;
                    if (dataContainers != null)
                    {
                        foreach (var container in dataContainers)
                        {
                            container.Value = null;
                        }
                    }
                }
            }

            if (result == DependencyProperty.UnsetValue || result == System.Windows.Data.Binding.DoNothing)
            {
                return(result);
            }

            if (!convertingBack && _chainedConverter != null)
            {
                try { result = _chainedConverter.Convert(result, targetType, parameter, culture); }
                catch (Exception e)
                {
                    EquationTokenizer.ThrowQuickConverterEvent(new ChainedConverterExceptionEventArgs(ConvertExpression, result, targetType, parameter, culture, false, _chainedConverter, this, e));
                    return(DependencyProperty.UnsetValue);
                }
            }

            if (result == DependencyProperty.UnsetValue || result == System.Windows.Data.Binding.DoNothing || result == null || 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);
        }
Esempio n. 18
0
 /* ----------------------------------------------------------------- */
 ///
 /// Convert
 ///
 /// <summary>
 /// Invokes the IValueConverter.Convert method.
 /// </summary>
 ///
 /// <param name="src">Object to invoke the Convert method.</param>
 /// <param name="value">Source value.</param>
 ///
 /// <returns>Result value.</returns>
 ///
 /* ----------------------------------------------------------------- */
 public T Convert <T>(IValueConverter src, object value) =>
 (T)src.Convert(value, typeof(T), null, CultureInfo.CurrentCulture);
 public ICssValue Convert(StringSource source) => converter.Convert(source);
 internal static IValueConverter AssertConvert <TValue, TConvertedValue>(this IValueConverter converter, TValue value, object parameter, TConvertedValue expectedConvertedValue, bool twoWay = false, bool backOnly = false, CultureInfo culture = null)
 {
     Assert.That(converter?.Convert(value, typeof(object), parameter, culture), Is.EqualTo(backOnly ? default(TConvertedValue) : expectedConvertedValue));
     Assert.That(converter?.ConvertBack(expectedConvertedValue, typeof(object), parameter, culture), Is.EqualTo(twoWay || backOnly ? value : default(TValue)));
     return(converter);
 }
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     return(doubleToStringConverter.Convert(value, targetType, parameter, culture));
 }
Esempio n. 22
0
 /// <summary>
 /// 绑定指定的值到属性,并使用指定的转换器。
 /// </summary>
 /// <param name="value">绑定的值。</param>
 /// <param name="converter">更新时,值转换器。</param>
 /// <param name="convertParameter">转换参数。</param>
 /// <param name="culture">区域信息。</param>
 /// <returns>返回已绑定的 <see cref="Forms.Binding"/> 实例。</returns>
 /// <exception cref="ArgumentException">给定数据为null时引发。</exception>
 /// <exception cref="ArgumentNullException">控件属性是已绑定到数据或<see cref="Forms.Binding"/> 未指定的有效列时引发。</exception>
 public IBindableProperty Binding(IValueObject value, IValueConverter converter, object convertParameter = null, CultureInfo culture = null)
 {
     BindingCore(value, i => converter.Convert(i, bindingProperty.PropertyType, converter, culture), i => converter.ConvertBack(i, value.Type, convertParameter, culture));
     return(this);
 }
Esempio n. 23
0
        public void _1_minute_shows_nonplural_minute()
        {
            var text = (string)_converter.Convert(60d, null, null, null);

            text.ShouldBe("Every 1 minute");
        }
 /// <summary>
 /// Runs Convert with TargetType and Parameter = null
 /// </summary>
 /// <typeparam name="TOutput">The expected output</typeparam>
 /// <param name="valueConverter">The value converter</param>
 /// <param name="input">The input to use for the converter</param>
 /// <param name="culture">The culture to use</param>
 /// <returns></returns>
 public static TOutput Convert <TOutput>(this IValueConverter valueConverter, object input, CultureInfo culture)
 {
     return((TOutput)valueConverter.Convert(input, null, null, culture));
 }
Esempio n. 25
0
 public ICssValue Convert(StringSource source)
 {
     return(converter.Convert(source));
 }
Esempio n. 26
0
		public object Convert(object value, Type targetType, IValueConverter valueConverter)
		{
			object result = value;
			
			if (valueConverter != null)
			{
				var parameter = GetConverterParameter();
				result = valueConverter.Convert(value, targetType, parameter, CultureInfo.CurrentUICulture);
			}
				
			if (targetType != null)
			{
				var typeCode = System.Convert.GetTypeCode(value);
				if (typeCode != TypeCode.Object && typeCode != TypeCode.Empty)
				{
					try					
					{
						result = System.Convert.ChangeType(result, targetType);
					}
					catch (InvalidCastException)
					{
					}
				}
			}

			return result;
		}
Esempio n. 27
0
 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
     CreateConverter();
     return(_converter.Convert(value, targetType, parameter, culture));
 }
Esempio n. 28
0
 public IPropertyValue Convert(IEnumerable <CssToken> value)
 {
     return(value.Any() ? _converter.Convert(value) : null);
 }
Esempio n. 29
0
        public void WithValidNumberReturnThisNumber(string str, decimal expected)
        {
            decimal result = obj.Convert(str, culture);

            Assert.Equal(expected, result);
        }
Esempio n. 30
0
 public override IDataObject GetDataObject(IEnumerable <M> models)
 {
     return(_dataObjectConverter.Convert(models, typeof(IDataObject), null, Thread.CurrentThread.CurrentUICulture) as IDataObject);
 }
 void TestEnumerableConverter <TCollection>(IValueConverter converter) where TCollection : IEnumerable
 {
     AssertHelper.AssertEnumerablesAreEqual(new string[] { "0", "1", "2" }, (TCollection)converter.Convert(new int[] { 0, 1, 2 }, typeof(TCollection), null, null));
 }
 public static IPropertyValue ConvertDefault(this IValueConverter converter)
 {
     return(converter.Convert(Enumerable.Empty <CssToken>()));
 }
Esempio n. 33
0
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture, IDataContext context)
 {
     return(_valueConverter.Convert(value, targetType, parameter, culture.Name));
 }
Esempio n. 34
0
 /// <summary>
 /// Converts the <paramref name="value" /> from string to string.
 /// </summary>
 /// <param name="value">The value as a string</param>
 /// <returns></returns>
 public string Convert(string value)
 {
     return(_converter.Convert(value));
 }