/// <summary> /// Tries to cast a value to a type, taking into account that the value may be a /// <see cref="BindingError"/>. /// </summary> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <returns>The cast value, or a <see cref="BindingError"/>.</returns> private static object CastOrDefault(object value, Type type) { var error = value as BindingError; if (error == null) { return(TypeUtilities.CastOrDefault(value, type)); } else { return(error); } }
/// <summary> /// Binds a <see cref="PerspexProperty"/> to an observable. /// </summary> /// <param name="property">The property.</param> /// <param name="source">The observable.</param> /// <param name="priority">The priority of the binding.</param> /// <returns> /// A disposable which can be used to terminate the binding. /// </returns> public IDisposable Bind( PerspexProperty property, IObservable <object> source, BindingPriority priority = BindingPriority.LocalValue) { Contract.Requires <ArgumentNullException>(property != null); VerifyAccess(); if (property.IsDirect) { property = GetRegistered(property); if (property.Setter == null) { throw new ArgumentException($"The property {property.Name} is readonly."); } _propertyLog.Verbose( "Bound {Property} to {Binding} with priority LocalValue", property, GetDescription(source)); return(source .Select(x => TypeUtilities.CastOrDefault(x, property.PropertyType)) .Subscribe(x => SetValue(property, x))); } else { PriorityValue v; if (!PerspexPropertyRegistry.Instance.IsRegistered(this, property)) { ThrowNotRegistered(property); } if (!_values.TryGetValue(property, out v)) { v = CreatePriorityValue(property); _values.Add(property, v); } _propertyLog.Verbose( "Bound {Property} to {Binding} with priority {Priority}", property, GetDescription(source), priority); return(v.Add(source, (int)priority)); } }
/// <summary> /// Tries to cast a value to a type, taking into account that the value may be a /// <see cref="BindingNotification"/>. /// </summary> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <returns>The cast value, or a <see cref="BindingNotification"/>.</returns> private static object CastOrDefault(object value, Type type) { var notification = value as BindingNotification; if (notification == null) { return(TypeUtilities.CastOrDefault(value, type)); } else { if (notification.HasValue) { notification.SetValue(TypeUtilities.CastOrDefault(notification.Value, type)); } return(notification); } }