| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586 |
- // Copyright (c) The Avalonia Project. All rights reserved.
- // Licensed under the MIT license. See licence.md file in the project root for full license information.
- using System;
- using System.Collections.Generic;
- using System.Reactive.Subjects;
- using Avalonia.Data;
- using Avalonia.Utilities;
- namespace Avalonia
- {
- /// <summary>
- /// Base class for avalonia properties.
- /// </summary>
- public abstract class AvaloniaProperty : IEquatable<AvaloniaProperty>
- {
- /// <summary>
- /// Represents an unset property value.
- /// </summary>
- public static readonly object UnsetValue = new UnsetValueType();
- private static int s_nextId;
- private readonly Subject<AvaloniaPropertyChangedEventArgs> _changed;
- private readonly PropertyMetadata _defaultMetadata;
- private readonly Dictionary<Type, PropertyMetadata> _metadata;
- private readonly Dictionary<Type, PropertyMetadata> _metadataCache = new Dictionary<Type, PropertyMetadata>();
- private bool _hasMetadataOverrides;
- /// <summary>
- /// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
- /// </summary>
- /// <param name="name">The name of the property.</param>
- /// <param name="valueType">The type of the property's value.</param>
- /// <param name="ownerType">The type of the class that registers the property.</param>
- /// <param name="metadata">The property metadata.</param>
- /// <param name="notifying">A <see cref="Notifying"/> callback.</param>
- protected AvaloniaProperty(
- string name,
- Type valueType,
- Type ownerType,
- PropertyMetadata metadata,
- Action<IAvaloniaObject, bool> notifying = null)
- {
- Contract.Requires<ArgumentNullException>(name != null);
- Contract.Requires<ArgumentNullException>(valueType != null);
- Contract.Requires<ArgumentNullException>(ownerType != null);
- Contract.Requires<ArgumentNullException>(metadata != null);
- if (name.Contains("."))
- {
- throw new ArgumentException("'name' may not contain periods.");
- }
- _changed = new Subject<AvaloniaPropertyChangedEventArgs>();
- _metadata = new Dictionary<Type, PropertyMetadata>();
- Name = name;
- PropertyType = valueType;
- OwnerType = ownerType;
- Notifying = notifying;
- Id = s_nextId++;
- _metadata.Add(ownerType, metadata);
- _defaultMetadata = metadata;
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
- /// </summary>
- /// <param name="source">The direct property to copy.</param>
- /// <param name="ownerType">The new owner type.</param>
- /// <param name="metadata">Optional overridden metadata.</param>
- protected AvaloniaProperty(
- AvaloniaProperty source,
- Type ownerType,
- PropertyMetadata metadata)
- {
- Contract.Requires<ArgumentNullException>(source != null);
- Contract.Requires<ArgumentNullException>(ownerType != null);
- _changed = source._changed;
- _metadata = new Dictionary<Type, PropertyMetadata>();
- Name = source.Name;
- PropertyType = source.PropertyType;
- OwnerType = ownerType;
- Notifying = source.Notifying;
- Id = source.Id;
- _defaultMetadata = source._defaultMetadata;
- // Properties that have different owner can't use fast path for metadata.
- _hasMetadataOverrides = true;
- if (metadata != null)
- {
- _metadata.Add(ownerType, metadata);
- }
- }
- /// <summary>
- /// Gets the name of the property.
- /// </summary>
- public string Name { get; }
- /// <summary>
- /// Gets the type of the property's value.
- /// </summary>
- public Type PropertyType { get; }
- /// <summary>
- /// Gets the type of the class that registered the property.
- /// </summary>
- public Type OwnerType { get; }
- /// <summary>
- /// Gets a value indicating whether the property inherits its value.
- /// </summary>
- public virtual bool Inherits => false;
- /// <summary>
- /// Gets a value indicating whether this is an attached property.
- /// </summary>
- public virtual bool IsAttached => false;
- /// <summary>
- /// Gets a value indicating whether this is a direct property.
- /// </summary>
- public virtual bool IsDirect => false;
- /// <summary>
- /// Gets a value indicating whether this is a readonly property.
- /// </summary>
- public virtual bool IsReadOnly => false;
- /// <summary>
- /// Gets an observable that is fired when this property changes on any
- /// <see cref="AvaloniaObject"/> instance.
- /// </summary>
- /// <value>
- /// An observable that is fired when this property changes on any
- /// <see cref="AvaloniaObject"/> instance.
- /// </value>
- public IObservable<AvaloniaPropertyChangedEventArgs> Changed => _changed;
- /// <summary>
- /// Gets a method that gets called before and after the property starts being notified on an
- /// object.
- /// </summary>
- /// <remarks>
- /// When a property changes, change notifications are sent to all property subscribers;
- /// for example via the <see cref="AvaloniaProperty.Changed"/> observable and and the
- /// <see cref="AvaloniaObject.PropertyChanged"/> event. If this callback is set for a property,
- /// then it will be called before and after these notifications take place. The bool argument
- /// will be true before the property change notifications are sent and false afterwards. This
- /// callback is intended to support Control.IsDataContextChanging.
- /// </remarks>
- public Action<IAvaloniaObject, bool> Notifying { get; }
- /// <summary>
- /// Gets the integer ID that represents this property.
- /// </summary>
- internal int Id { get; }
- internal bool HasChangedSubscriptions => _changed?.HasObservers ?? false;
- /// <summary>
- /// Provides access to a property's binding via the <see cref="AvaloniaObject"/>
- /// indexer.
- /// </summary>
- /// <param name="property">The property.</param>
- /// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
- public static IndexerDescriptor operator !(AvaloniaProperty property)
- {
- return new IndexerDescriptor
- {
- Priority = BindingPriority.LocalValue,
- Property = property,
- };
- }
- /// <summary>
- /// Provides access to a property's template binding via the <see cref="AvaloniaObject"/>
- /// indexer.
- /// </summary>
- /// <param name="property">The property.</param>
- /// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
- public static IndexerDescriptor operator ~(AvaloniaProperty property)
- {
- return new IndexerDescriptor
- {
- Priority = BindingPriority.TemplatedParent,
- Property = property,
- };
- }
- /// <summary>
- /// Tests two <see cref="AvaloniaProperty"/>s for equality.
- /// </summary>
- /// <param name="a">The first property.</param>
- /// <param name="b">The second property.</param>
- /// <returns>True if the properties are equal, otherwise false.</returns>
- public static bool operator ==(AvaloniaProperty a, AvaloniaProperty b)
- {
- if (object.ReferenceEquals(a, b))
- {
- return true;
- }
- else if (((object)a == null) || ((object)b == null))
- {
- return false;
- }
- else
- {
- return a.Equals(b);
- }
- }
- /// <summary>
- /// Tests two <see cref="AvaloniaProperty"/>s for inequality.
- /// </summary>
- /// <param name="a">The first property.</param>
- /// <param name="b">The second property.</param>
- /// <returns>True if the properties are equal, otherwise false.</returns>
- public static bool operator !=(AvaloniaProperty a, AvaloniaProperty b)
- {
- return !(a == b);
- }
- /// <summary>
- /// Registers a <see cref="AvaloniaProperty"/>.
- /// </summary>
- /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
- /// <typeparam name="TValue">The type of the property's value.</typeparam>
- /// <param name="name">The name of the property.</param>
- /// <param name="defaultValue">The default value of the property.</param>
- /// <param name="inherits">Whether the property inherits its value.</param>
- /// <param name="defaultBindingMode">The default binding mode for the property.</param>
- /// <param name="validate">A value validation callback.</param>
- /// <param name="coerce">A value coercion callback.</param>
- /// <param name="notifying">
- /// A method that gets called before and after the property starts being notified on an
- /// object; the bool argument will be true before and false afterwards. This callback is
- /// intended to support IsDataContextChanging.
- /// </param>
- /// <returns>A <see cref="StyledProperty{TValue}"/></returns>
- public static StyledProperty<TValue> Register<TOwner, TValue>(
- string name,
- TValue defaultValue = default(TValue),
- bool inherits = false,
- BindingMode defaultBindingMode = BindingMode.OneWay,
- Func<TValue, bool> validate = null,
- Func<IAvaloniaObject, TValue, TValue> coerce = null,
- Action<IAvaloniaObject, bool> notifying = null)
- where TOwner : IAvaloniaObject
- {
- Contract.Requires<ArgumentNullException>(name != null);
- var metadata = new StyledPropertyMetadata<TValue>(
- defaultValue,
- defaultBindingMode: defaultBindingMode,
- coerce: coerce);
- var result = new StyledProperty<TValue>(
- name,
- typeof(TOwner),
- metadata,
- inherits,
- validate,
- notifying);
- AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
- return result;
- }
- /// <summary>
- /// Registers an attached <see cref="AvaloniaProperty"/>.
- /// </summary>
- /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
- /// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
- /// <typeparam name="TValue">The type of the property's value.</typeparam>
- /// <param name="name">The name of the property.</param>
- /// <param name="defaultValue">The default value of the property.</param>
- /// <param name="inherits">Whether the property inherits its value.</param>
- /// <param name="defaultBindingMode">The default binding mode for the property.</param>
- /// <param name="validate">A value validation callback.</param>
- /// <param name="coerce">A value coercion callback.</param>
- /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
- public static AttachedProperty<TValue> RegisterAttached<TOwner, THost, TValue>(
- string name,
- TValue defaultValue = default(TValue),
- bool inherits = false,
- BindingMode defaultBindingMode = BindingMode.OneWay,
- Func<TValue, bool> validate = null,
- Func<IAvaloniaObject, TValue, TValue> coerce = null)
- where THost : IAvaloniaObject
- {
- Contract.Requires<ArgumentNullException>(name != null);
- var metadata = new StyledPropertyMetadata<TValue>(
- defaultValue,
- defaultBindingMode: defaultBindingMode,
- coerce: coerce);
- var result = new AttachedProperty<TValue>(name, typeof(TOwner), metadata, inherits, validate);
- var registry = AvaloniaPropertyRegistry.Instance;
- registry.Register(typeof(TOwner), result);
- registry.RegisterAttached(typeof(THost), result);
- return result;
- }
- /// <summary>
- /// Registers an attached <see cref="AvaloniaProperty"/>.
- /// </summary>
- /// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
- /// <typeparam name="TValue">The type of the property's value.</typeparam>
- /// <param name="name">The name of the property.</param>
- /// <param name="ownerType">The type of the class that is registering the property.</param>
- /// <param name="defaultValue">The default value of the property.</param>
- /// <param name="inherits">Whether the property inherits its value.</param>
- /// <param name="defaultBindingMode">The default binding mode for the property.</param>
- /// <param name="validate">A value validation callback.</param>
- /// <param name="coerce">A value coercion callback.</param>
- /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
- public static AttachedProperty<TValue> RegisterAttached<THost, TValue>(
- string name,
- Type ownerType,
- TValue defaultValue = default(TValue),
- bool inherits = false,
- BindingMode defaultBindingMode = BindingMode.OneWay,
- Func<TValue, bool> validate = null,
- Func<IAvaloniaObject, TValue, TValue> coerce = null)
- where THost : IAvaloniaObject
- {
- Contract.Requires<ArgumentNullException>(name != null);
- var metadata = new StyledPropertyMetadata<TValue>(
- defaultValue,
- defaultBindingMode: defaultBindingMode,
- coerce: coerce);
- var result = new AttachedProperty<TValue>(name, ownerType, metadata, inherits, validate);
- var registry = AvaloniaPropertyRegistry.Instance;
- registry.Register(ownerType, result);
- registry.RegisterAttached(typeof(THost), result);
- return result;
- }
- /// <summary>
- /// Registers a direct <see cref="AvaloniaProperty"/>.
- /// </summary>
- /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
- /// <typeparam name="TValue">The type of the property's value.</typeparam>
- /// <param name="name">The name of the property.</param>
- /// <param name="getter">Gets the current value of the property.</param>
- /// <param name="setter">Sets the value of the property.</param>
- /// <param name="unsetValue">The value to use when the property is cleared.</param>
- /// <param name="defaultBindingMode">The default binding mode for the property.</param>
- /// <param name="enableDataValidation">
- /// Whether the property is interested in data validation.
- /// </param>
- /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
- public static DirectProperty<TOwner, TValue> RegisterDirect<TOwner, TValue>(
- string name,
- Func<TOwner, TValue> getter,
- Action<TOwner, TValue> setter = null,
- TValue unsetValue = default(TValue),
- BindingMode defaultBindingMode = BindingMode.OneWay,
- bool enableDataValidation = false)
- where TOwner : IAvaloniaObject
- {
- Contract.Requires<ArgumentNullException>(name != null);
- Contract.Requires<ArgumentNullException>(getter != null);
- var metadata = new DirectPropertyMetadata<TValue>(
- unsetValue: unsetValue,
- defaultBindingMode: defaultBindingMode);
- var result = new DirectProperty<TOwner, TValue>(
- name,
- getter,
- setter,
- metadata,
- enableDataValidation);
- AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
- return result;
- }
- /// <summary>
- /// Returns a binding accessor that can be passed to <see cref="AvaloniaObject"/>'s []
- /// operator to initiate a binding.
- /// </summary>
- /// <returns>A <see cref="IndexerDescriptor"/>.</returns>
- /// <remarks>
- /// The ! and ~ operators are short forms of this.
- /// </remarks>
- public IndexerDescriptor Bind()
- {
- return new IndexerDescriptor
- {
- Property = this,
- };
- }
- /// <inheritdoc/>
- public override bool Equals(object obj)
- {
- var p = obj as AvaloniaProperty;
- return p != null && Equals(p);
- }
- /// <inheritdoc/>
- public bool Equals(AvaloniaProperty other)
- {
- return other != null && Id == other.Id;
- }
- /// <inheritdoc/>
- public override int GetHashCode()
- {
- return Id;
- }
- /// <summary>
- /// Gets the property metadata for the specified type.
- /// </summary>
- /// <typeparam name="T">The type.</typeparam>
- /// <returns>
- /// The property metadata.
- /// </returns>
- public PropertyMetadata GetMetadata<T>() where T : IAvaloniaObject
- {
- return GetMetadata(typeof(T));
- }
- /// <summary>
- /// Gets the property metadata for the specified type.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <returns>
- /// The property metadata.
- /// </returns>
- ///
- public PropertyMetadata GetMetadata(Type type)
- {
- if (!_hasMetadataOverrides)
- {
- return _defaultMetadata;
- }
- return GetMetadataWithOverrides(type);
- }
- /// <summary>
- /// Checks whether the <paramref name="value"/> is valid for the property.
- /// </summary>
- /// <param name="value">The value.</param>
- /// <returns>True if the value is valid, otherwise false.</returns>
- public bool IsValidValue(object value)
- {
- return TypeUtilities.TryConvertImplicit(PropertyType, value, out value);
- }
- /// <summary>
- /// Gets the string representation of the property.
- /// </summary>
- /// <returns>The property's string representation.</returns>
- public override string ToString()
- {
- return Name;
- }
- /// <summary>
- /// Notifies the <see cref="Changed"/> observable.
- /// </summary>
- /// <param name="e">The observable arguments.</param>
- internal void NotifyChanged(AvaloniaPropertyChangedEventArgs e)
- {
- _changed.OnNext(e);
- }
- /// <summary>
- /// Routes an untyped ClearValue call to a typed call.
- /// </summary>
- /// <param name="o">The object instance.</param>
- internal abstract void RouteClearValue(IAvaloniaObject o);
- /// <summary>
- /// Routes an untyped GetValue call to a typed call.
- /// </summary>
- /// <param name="o">The object instance.</param>
- internal abstract object RouteGetValue(IAvaloniaObject o);
- /// <summary>
- /// Routes an untyped SetValue call to a typed call.
- /// </summary>
- /// <param name="o">The object instance.</param>
- /// <param name="value">The value.</param>
- /// <param name="priority">The priority.</param>
- internal abstract void RouteSetValue(
- IAvaloniaObject o,
- object value,
- BindingPriority priority);
- /// <summary>
- /// Routes an untyped Bind call to a typed call.
- /// </summary>
- /// <param name="o">The object instance.</param>
- /// <param name="source">The binding source.</param>
- /// <param name="priority">The priority.</param>
- internal abstract IDisposable RouteBind(
- IAvaloniaObject o,
- IObservable<BindingValue<object>> source,
- BindingPriority priority);
- internal abstract void RouteInheritanceParentChanged(AvaloniaObject o, IAvaloniaObject oldParent);
- /// <summary>
- /// Overrides the metadata for the property on the specified type.
- /// </summary>
- /// <param name="type">The type.</param>
- /// <param name="metadata">The metadata.</param>
- protected void OverrideMetadata(Type type, PropertyMetadata metadata)
- {
- Contract.Requires<ArgumentNullException>(type != null);
- Contract.Requires<ArgumentNullException>(metadata != null);
- if (_metadata.ContainsKey(type))
- {
- throw new InvalidOperationException(
- $"Metadata is already set for {Name} on {type}.");
- }
- var baseMetadata = GetMetadata(type);
- metadata.Merge(baseMetadata, this);
- _metadata.Add(type, metadata);
- _metadataCache.Clear();
- _hasMetadataOverrides = true;
- }
- private PropertyMetadata GetMetadataWithOverrides(Type type)
- {
- if (type is null)
- {
- throw new ArgumentNullException(nameof(type));
- }
- if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
- {
- return result;
- }
- Type currentType = type;
- while (currentType != null)
- {
- if (_metadata.TryGetValue(currentType, out result))
- {
- _metadataCache[type] = result;
- return result;
- }
- currentType = currentType.BaseType;
- }
- _metadataCache[type] = _defaultMetadata;
- return _defaultMetadata;
- }
- }
- /// <summary>
- /// Class representing the <see cref="AvaloniaProperty.UnsetValue"/>.
- /// </summary>
- public sealed class UnsetValueType
- {
- internal UnsetValueType() { }
- /// <summary>
- /// Returns the string representation of the <see cref="AvaloniaProperty.UnsetValue"/>.
- /// </summary>
- /// <returns>The string "(unset)".</returns>
- public override string ToString() => "(unset)";
- }
- }
|