Exemplo n.º 1
0
        public void SetValue(object value, bool isToSource, IValueConverter converter = null)
        {
            if (property == null)
            {
                Debug.LogError("SetValue property NULL");
                return;
            }

            if (field != null)
            {
                var parentProp = property.GetValue(propertyOwner, null);

                if (converter != null)
                {
                    if (isToSource)
                    {
                        field.SetValue(parentProp, converter.ConvertBack(value, field.GetType(), null));
                    }
                    else
                    {
                        field.SetValue(parentProp, converter.Convert(value, field.GetType(), null));
                    }
                }
                else if (value is IConvertible)
                {
                    field.SetValue(parentProp, Convert.ChangeType(value, field.FieldType));
                }
                else
                {
                    field.SetValue(parentProp, value);
                }

                property.SetValue(propertyOwner, parentProp);
            }

            else
            {
                if (converter != null)
                {
                    if (isToSource)
                    {
                        property.SetValue(propertyOwner, converter.ConvertBack(value, property.PropertyType, null));
                    }
                    else
                    {
                        property.SetValue(propertyOwner, converter.Convert(value, property.PropertyType, null));
                    }
                }
                else if (value is IConvertible)
                {
                    property.SetValue(propertyOwner, Convert.ChangeType(value, property.PropertyType));
                }
                else
                {
                    property.SetValue(propertyOwner, value, null);
                }
            }
        }
Exemplo n.º 2
0
        public void UpdateSource()
        {
            if (!IsBound)
            {
                Debug.LogWarning("Unbound");
                return;
            }

            var value = targetProperty.GetValue(target);

            // use converter
            if (converter != null)
            {
                value = converter.ConvertBack(value, sourceProperty.PropertyType);
            }

            try
            {
                // set value to source
                sourceProperty.SetValue(source, value);
            }
            catch (Exception ex)
            {
                Debug.LogError(string.Format("Failed to set value to source. sourceType={0}, targetType={1}, exception={2}",
                                             sourceProperty.PropertyType, targetProperty.PropertyType, ex.Message), target as UnityEngine.Object);
            }
        }
Exemplo n.º 3
0
        private void PushTargetToSourceCore(object state)
        {
            if (_changeLatch)
            {
                return;
            }

            //copy changes from target to source
            var newValue = TargetPropertyExpression.NormalizedValue;

            if (_converter != null)
            {
                newValue = _converter.ConvertBack(newValue, SourcePropertyExpression.PropertyType, _converterParameter, _converterCulture);
            }

            _changeLatch = true;

            try
            {
                if (SourcePropertyExpression != null)
                {
                    SourcePropertyExpression.Value = newValue;
                }
            }
            finally
            {
                _changeLatch = false;
            }
        }
Exemplo n.º 4
0
        public void Convert_ConvertBackFuncIsNull_ReturnsDependencyPropertyUnsetValue()
        {
            Target = new TypedValueConverterBase <int, string>((value, parameter, culture) => string.Empty, null);

            Target.ConvertBack("Valid string value", typeof(int), null, null)
            .Should().Be(DependencyProperty.UnsetValue);
        }
Exemplo n.º 5
0
        public object GetSettingValue(Type valueType)
        {
            object value = GetSettings()[SettingName];

            if (value == null || value.GetType() == valueType)
            {
                return(value);
            }

            else if (ValueConverter != null)
            {
                return(ValueConverter.ConvertBack(value, valueType, null, new System.Globalization.CultureInfo("en-US")));
            }

            else
            {
                var converter = TypeDescriptor.GetConverter(valueType);
                if (converter != null && converter.CanConvertFrom(value.GetType()))
                {
                    return(converter.ConvertFrom(value));
                }
                else
                {
                    return(null);
                }
            }
        }
Exemplo n.º 6
0
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                var val = value;

                if (_converter != null)
                {
                    val = _converter.ConvertBack(value, targetType, parameter, culture);
                }

                var changeGroup = _designItem.OpenGroup("Property: " + _propertyName);

                try
                {
                    var property = _designItem.Properties.GetProperty(_propertyName);

                    property.SetValue(val);


                    if (!_singleItemProperty && _designItem.Services.Selection.SelectedItems.Count > 1)
                    {
                        var msg = MessageBoxResult.Yes;
                        if (_askWhenMultipleItemsSelected)
                        {
                            msg = MessageBox.Show("Apply changes to all selected Items", "", MessageBoxButton.YesNo);
                        }
                        if (msg == MessageBoxResult.Yes)
                        {
                            foreach (var item in _designItem.Services.Selection.SelectedItems)
                            {
                                try
                                {
                                    if (_property != null)
                                    {
                                        property = item.Properties.GetProperty(_property);
                                    }
                                    else
                                    {
                                        property = item.Properties.GetProperty(_propertyName);
                                    }
                                }
                                catch (Exception)
                                { }
                                if (property != null)
                                {
                                    property.SetValue(val);
                                }
                            }
                        }
                    }

                    changeGroup.Commit();
                }
                catch (Exception)
                {
                    changeGroup.Abort();
                }

                return(val);
            }
Exemplo n.º 7
0
 /// <summary>
 /// Converts the binding using the specified <paramref name="converter"/> object.
 /// </summary>
 /// <returns>A new binding that will be converted using the specified IValueConverter.</returns>
 /// <param name="converter">Converter object to use when converting to/from the value</param>
 /// <param name="propertyType">Type for the converter to convert to</param>
 /// <param name="conveterParameter">Parameter to pass to the converter.</param>
 /// <param name="culture">Culture to use for conversion, null to use invariant culture.</param>
 public IndirectBinding <object> Convert(IValueConverter converter, Type propertyType, object conveterParameter = null, CultureInfo culture = null)
 {
     culture = culture ?? CultureInfo.InvariantCulture;
     return(Convert(
                val => converter.Convert(val, propertyType, conveterParameter, culture),
                val => (T)converter.ConvertBack(val, typeof(T), conveterParameter, culture)
                ));
 }
Exemplo n.º 8
0
 protected bool ConvertBack(object val, Type targetType, out object result)
 {
     if (_valueConverter != null)
     {
         return(_valueConverter.ConvertBack(val, targetType, _converterParameter, ServiceRegistration.Get <ILocalization>().CurrentCulture, out result));
     }
     return(TypeConverter.Convert(val, targetType, out result));
 }
Exemplo n.º 9
0
 protected override object CoerceBeforeConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
 {
     if (externalConverter != null)
     {
         return(externalConverter.ConvertBack(value, backConversionType, parameter, culture));
     }
     return(base.CoerceBeforeConvertBack(value, targetTypes, parameter, culture));
 }
Exemplo n.º 10
0
        public void ConvertBack_ConvertBackFuncReturnsIntFor42String_ReturnsEqualValue()
        {
            const int expectedValue = 42;

            Target = new TypedValueConverterBase <int, string>((i, o, c) => string.Empty, (s, o, c) => expectedValue);

            Target.ConvertBack("42", typeof(int), null, null)
            .Should().Be(expectedValue);
        }
Exemplo n.º 11
0
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (multiValueConverter != null)
                {
                    value = multiValueConverter.ConvertBack(value, targetType, parameter, culture);
                }

                return(value);
            }
 protected override object CoerceBeforeConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
 {
     if (externalConverter != null)
     {
         var t = targetTypes != null && targetTypes.Count() == 1 ? targetTypes[0] : backConversionType;
         return(externalConverter.ConvertBack(value, t, parameter, culture));
     }
     return(base.CoerceBeforeConvertBack(value, targetTypes, parameter, culture));
 }
Exemplo n.º 13
0
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                if (converter != null)
                {
                    return(converter.ConvertBack(value, targetType, parameter, culture));
                }

                return(Binding.DoNothing);
            }
Exemplo n.º 14
0
        private static void VerifyConvert(IValueConverter converter, string input, double?expected)
        {
            var value = (double?)converter.ConvertBack(input, null, null, null);

            value.Should().Be(expected);
            var text = (string)converter.Convert(value, null, null, null);

            text.Should().Be(input);
        }
 private static void OnNetworkTableChange(ITable table, string key, Value v, NotifyFlags flags)
 {
     try
     {
         //multiple objects could be bound to this key
         foreach (INotifyPropertyChanged source in propertyLookup.Keys)
         {
             OneToOneConversionMap <string, string> conversionMap = propertyLookup[source];
             ITable boundTable    = customTables[source];
             object bindingSource = (source is DependencyNotifyListener) ? (object)(source as DependencyNotifyListener).source : source;
             if (table.ToString() != boundTable.ToString())
             {
                 continue;
             }
             if (conversionMap.TryGetBySecond(key, out string property))
             {
                 //the property that changed is bound to this object
                 //grab the converter and use it if needed
                 IValueConverter converter = conversionMap.GetConverterByFirst(property);
                 PropertyInfo    inf       = bindingSource.GetType().GetProperty(property);
                 //issue using v for some reason
                 object value = NetworkUtil.ReadValue(boundTable.GetValue(key, null));
                 if (converter != null)
                 {
                     //in an NTConverter (required in API) the null values are never used so we don't need to set them
                     object attemptedVal = converter.ConvertBack(value, null, null, null);
                     //in case the conversion was invalid
                     if (attemptedVal != DependencyProperty.UnsetValue)
                     {
                         value = attemptedVal;
                     }
                 }
                 //correct any type inconsistencies (eg if we want to display an integer from the network, which only stores doubles)
                 if (value != null && value.GetType() != inf.PropertyType)
                 {
                     Type targetType = inf.PropertyType;
                     if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable <>))
                     {
                         targetType = targetType.GetGenericArguments()[0];
                     }
                     //anything still here can make an invalid cast to let them know to use a converter
                     value = Convert.ChangeType(value, targetType);
                 }
                 //write to the object
                 assignmentDispatch.Invoke(() => inf.SetValue(bindingSource, value));
             }
         }
     }
     catch (InvalidOperationException e)
     {
         if (!e.Message.StartsWith("Collection was modified"))
         {
             throw e;
         }
     }
 }
Exemplo n.º 16
0
        void PerformTwoWayConverterTest(IValueConverter converter, object input, object expectedValue, object parameter)
        {
            var culture = CultureInfo.CurrentUICulture;

            var convertedValue   = converter.Convert(input, null, parameter, culture);
            var convertBackValue = converter.ConvertBack(expectedValue, null, parameter, culture);

            Assert.AreEqual(expectedValue, convertedValue);
            Assert.AreEqual(input, convertBackValue);
        }
Exemplo n.º 17
0
     public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
     {
         if (_lastConverter == null)
         {
             return new object[] { value }
         }
         ;
         return(new object[] { _lastConverter.ConvertBack(value, targetTypes[0], _lastParameter, culture) });
     }
 }
Exemplo n.º 18
0
        public void ValueChangeCheck(string s)
        {
            System.Object res = s;
            if (vc != null)
            {
                res = vc.ConvertBack(res, res.GetType(), null, null);
            }

            this.obj.GetType().GetProperty(this.path).SetValue(this.obj, res);
        }
Exemplo n.º 19
0
        /// <summary>
        /// Binds column to <see cref="TextBox"/> with specified value converter and culture info.
        /// </summary>
        /// <param name="source">The source column.</param>
        /// <param name="converter">The value converter.</param>
        /// <param name="cultureInfo">The culture info.</param>
        /// <param name="flushErrorMessage">The conversion error message when flushing data from binding to source model.</param>
        /// <returns>The row binding object.</returns>
        public static RowBinding <TextBox> BindToTextBox(this Column source, IValueConverter converter, CultureInfo cultureInfo, string flushErrorMessage = null)
        {
            source.VerifyNotNull(nameof(source));
            converter.VerifyNotNull(nameof(converter));
            cultureInfo.VerifyNotNull(nameof(cultureInfo));

            return(new RowBinding <TextBox>(onSetup: (v, p) => v.Setup(), onCleanup: (v, p) => v.Cleanup(), onRefresh: (v, p) =>
            {
                if (!v.GetIsEditing())
                {
                    v.Text = Convert(p[source], converter, cultureInfo);
                }
            }).BeginInput(TextBox.TextProperty, TextBox.LostFocusEvent)
                   .WithFlushingValidator(v =>
            {
                try
                {
                    var result = converter.ConvertBack(v.Text, source.DataType, null, cultureInfo);
                    if (result == DependencyProperty.UnsetValue)
                    {
                        return GetInvalidInputErrorMessage(flushErrorMessage, source.DataType);
                    }
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }
                return null;
            })
                   .WithFlush(source, (p, v) =>
            {
                var value = converter.ConvertBack(v.Text, source.DataType, null, cultureInfo);
                var oldValue = p[source];
                if (Equals(oldValue, value))
                {
                    return false;
                }
                p[source] = value;
                return true;
            })
                   .EndInput());
        }
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                if (Converter == null)
                {
                    return new object[] { value }
                }
                ;                                                     // Required for VS design-time

                return(new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) });
            }
        }
Exemplo n.º 21
0
 public void DstUpdated()
 {
     if (_converter != null)
     {
         _src.SetValue(_converter.ConvertBack(_dst.GetValue(), _src.property.PropertyType, null));
     }
     else
     {
         _src.SetValue(Convert.ChangeType(_dst.GetValue(), _src.property.PropertyType));
     }
 }
Exemplo n.º 22
0
    public void IdenticalThroughConversionCycle()
    {
        for (int i = 0; i < 31; i++)
        {
            Rgb15 initial  = new(i, 0, 0);
            Color midpoint = (Color)_converter.Convert(initial, typeof(Color), null, null);
            Rgb15 final    = (Rgb15)_converter.ConvertBack(midpoint, typeof(Rgb15), null, null);

            final.Should().Be(initial);
        }
    }
Exemplo n.º 23
0
 public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (converter != null)
     {
         return(converter.ConvertBack(value, targetType, parameter, culture));
     }
     else
     {
         throw new NotSupportedException();
     }
 }
Exemplo n.º 24
0
 protected override void OnParse(ConvertEventArgs cevent)
 {
     if (_converter != null)
     {
         cevent.Value = _converter.ConvertBack(cevent.Value,
                                               cevent.DesiredType, _converterParameter, _converterCulture);
     }
     else
     {
         base.OnParse(cevent);
     }
 }
 protected override void OnParse(ConvertEventArgs cevent)
 {
     if (_converter == null)
     {
         base.OnParse(cevent);
     }
     else
     {
         object valueFromCtl = _converter.ConvertBack(cevent.Value, cevent.DesiredType, _converterParameter, _converterCulture);
         cevent.Value = valueFromCtl;
     }
 }
Exemplo n.º 26
0
        public void ConvertBack_ValueIsNotTargetType_ThrowsArgumentException()
        {
            Target = new TypedValueConverterBase <int, string>((i, o, c) => string.Empty, (s, o, c) => 0);

            var convertBack = new Action(() => Target.ConvertBack(
                                             42, //Not target type (string)
                                             typeof(int), null, null));

            convertBack.ShouldThrow <ArgumentException>()
            .WithMessage("Value must be of type " + typeof(string) + "*")
            .And.ParamName.Should().Be("value");
        }
        private static void VerifyConvert(object?source)
        {
            var expected = _reference.Convert(source, null, null, null);
            var result   = _target.Convert(source, null, null, null);

            Assert.AreEqual(expected, result);

            expected = _reference.ConvertBack(source, null, null, null);
            result   = _target.ConvertBack(source, null, null, null);

            Assert.AreEqual(expected, result);
        }
Exemplo n.º 28
0
        public void ConvertBack_TargetTypeIsNotConverterSourceType_ThrowsArgumentException()
        {
            Target = new TypedValueConverterBase <int, string>((i, o, c) => string.Empty, (s, o, c) => 0);

            var convert = new Action(() => Target.ConvertBack("A valid string value",
                                                              typeof(bool), //Not source type of converter
                                                              null, null));

            convert.ShouldThrow <ArgumentException>()
            .WithMessage("TargetType must be " + typeof(int) + "*")
            .And.ParamName.Should().Be("targetType");
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            if (_chainedConverter != null)
            {
                try { value = _chainedConverter.ConvertBack(value, typeof(object), parameter, culture); }
                catch (Exception e)
                {
                    EquationTokenizer.ThrowQuickConverterEvent(new ChainedConverterExceptionEventArgs(ConvertExpression, value, typeof(object), parameter, culture, true, _chainedConverter, this, e));
                    return(new object[targetTypes.Length].Select(o => value).ToArray());
                }

                if (value == DependencyProperty.UnsetValue || value == System.Windows.Data.Binding.DoNothing)
                {
                    return(new object[targetTypes.Length].Select(o => value).ToArray());
                }
            }

            object[] ret = new object[_convertBack.Length];

            if (ValueType != null && !ValueType.IsInstanceOfType(value))
            {
                for (int i = 0; i < ret.Length; ++i)
                {
                    ret[i] = System.Windows.Data.Binding.DoNothing;
                }
                return(ret);
            }

            for (int i = 0; i < _convertBack.Length; ++i)
            {
                try { ret[i] = _convertBack[i](value, _values); }
                catch (Exception e)
                {
                    LastException = e;
                    ++ExceptionCount;
                    if (Debugger.IsAttached)
                    {
                        Console.WriteLine("QuickMultiConverter Exception (\"" + ConvertBackExpression[i] + "\") - " + e.Message + (e.InnerException != null ? " (Inner - " + e.InnerException.Message + ")" : ""));
                    }
                    EquationTokenizer.ThrowQuickConverterEvent(new RuntimeMultiConvertExceptionEventArgs(ConvertBackExpression[i], ConvertBackExpressionDebugView[i], null, _pIndices, value, _values, parameter, this, e));
                    ret[i] = DependencyProperty.UnsetValue;
                }
                ret[i] = CastResult(ret[i], targetTypes[i]);
            }
            if (_fromDataContainers != null)
            {
                foreach (var container in _fromDataContainers)
                {
                    container.Value = null;
                }
            }
            return(ret);
        }
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (lastConverter == null)
            {
                return new object[] { value }
            }
            ;
            return(new object[] { lastConverter.ConvertBack(value, targetTypes[0], lastParameter, culture) });
        }

        #endregion IMultiValueConverter Members
    }
 public void ConvertBackWithNullParameter_ShouldThrowArgumentNullException(IValueConverter converter)
 {
     try
     {
         result = converter.ConvertBack(null, null, null, "");
         Assert.Fail("An exception should have been thrown");
     }
     catch (ArgumentNullException exception)
     {
         StringAssert.Contains(exception.Message, "");
     }
     catch (Exception e)
     {
         Assert.Fail("The wrong exception has been thrown");
     }
 }
Exemplo n.º 32
0
        /// <summary>
        /// Checks to see if a given value matches a property's original value,
        /// and updates the ability to commit the edit if not.
        /// </summary>
        /// <param name="propertyName">The name of the property to check against.</param>
        /// <param name="value">The value to check against.</param>
        /// <param name="doConversion">Whether or not to convert the value to the original type.</param>
        /// <param name="originalType">The original type.</param>
        /// <param name="valueConverter">The IValueConverter to use for conversion.</param>
        /// <param name="converterParameter">The converter parameter.</param>
        /// <param name="converterCulture">The converter culture.</param>
        private void CheckIfPropertyEditedAndUpdate(
            string propertyName,
            object value,
            bool doConversion,
            Type originalType,
            IValueConverter valueConverter,
            object converterParameter,
            CultureInfo converterCulture)
        {
            object originalValue;

            if (!this._editablePropertiesOriginalValues.TryGetValue(propertyName, out originalValue))
            {
                return;
            }

            if (doConversion && value != null)
            {
                // Attempt to convert the value provided to the type of the original type.
                // If the conversion fails, just keep it as is.
                try
                {
                    if (valueConverter != null)
                    {
                        value = valueConverter.ConvertBack(value, originalType, converterParameter, converterCulture);
                    }
                    else
                    {
                        value = Convert.ChangeType(value, originalType, converterCulture);
                    }
                }
                catch (InvalidCastException)
                {
                }
                catch (FormatException)
                {
                }
                catch (OverflowException)
                {
                }
            }

            bool valueEqualsOriginal =
                (value == null && originalValue == null) ||
                (value != null && originalValue != null && value.Equals(originalValue));

            if (valueEqualsOriginal &&
                this._editedProperties.Contains(propertyName))
            {
                this._editedProperties.Remove(propertyName);
                SetAllCanPropertiesAndUpdate(this, false /* onlyUpdateStates */);
            }
            else if (!valueEqualsOriginal &&
                !this._editedProperties.Contains(propertyName))
            {
                this._editedProperties.Add(propertyName);
                SetAllCanPropertiesAndUpdate(this, false /* onlyUpdateStates */);
            }
        }
        private object ConvertBackHelper(IValueConverter converter,
                                         object value,
                                         Type sourceType,
                                         object parameter,
                                         CultureInfo culture)
        {
            Invariant.Assert(converter != 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
            {
                convertedValue = converter.ConvertBack(value, sourceType, 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
                ex = CriticalExceptions.Unwrap(ex);
                if (CriticalExceptions.IsCriticalApplicationException(ex))
                    throw;

                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error,
                        TraceData.BadConverterForUpdate(
                            AvTrace.ToStringHelper(Value),
                            AvTrace.TypeName(value)),
                        this, ex);
                }

                ProcessException(ex, ValidatesOnExceptions);
                convertedValue = DependencyProperty.UnsetValue;
            }
            catch // non CLS compliant exception
            {
                if (TraceData.IsEnabled)
                {
                    TraceData.Trace(TraceEventType.Error,
                        TraceData.BadConverterForUpdate(
                            AvTrace.ToStringHelper(Value),
                            AvTrace.TypeName(value)),
                        this);
                }
                convertedValue = DependencyProperty.UnsetValue;
            }

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

            return convertedValue;
        }