AvaloniaProperty.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Diagnostics;
  6. using System.Reactive.Subjects;
  7. using System.Reflection;
  8. using Avalonia.Data;
  9. using Avalonia.Utilities;
  10. namespace Avalonia
  11. {
  12. /// <summary>
  13. /// Base class for avalonia properties.
  14. /// </summary>
  15. public abstract class AvaloniaProperty : IEquatable<AvaloniaProperty>
  16. {
  17. /// <summary>
  18. /// Represents an unset property value.
  19. /// </summary>
  20. public static readonly object UnsetValue = new UnsetValueType();
  21. private static int s_nextId;
  22. private readonly Subject<AvaloniaPropertyChangedEventArgs> _initialized;
  23. private readonly Subject<AvaloniaPropertyChangedEventArgs> _changed;
  24. private readonly PropertyMetadata _defaultMetadata;
  25. private readonly Dictionary<Type, PropertyMetadata> _metadata;
  26. private readonly Dictionary<Type, PropertyMetadata> _metadataCache = new Dictionary<Type, PropertyMetadata>();
  27. private bool _hasMetadataOverrides;
  28. /// <summary>
  29. /// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
  30. /// </summary>
  31. /// <param name="name">The name of the property.</param>
  32. /// <param name="valueType">The type of the property's value.</param>
  33. /// <param name="ownerType">The type of the class that registers the property.</param>
  34. /// <param name="metadata">The property metadata.</param>
  35. /// <param name="notifying">A <see cref="Notifying"/> callback.</param>
  36. protected AvaloniaProperty(
  37. string name,
  38. Type valueType,
  39. Type ownerType,
  40. PropertyMetadata metadata,
  41. Action<IAvaloniaObject, bool> notifying = null)
  42. {
  43. Contract.Requires<ArgumentNullException>(name != null);
  44. Contract.Requires<ArgumentNullException>(valueType != null);
  45. Contract.Requires<ArgumentNullException>(ownerType != null);
  46. Contract.Requires<ArgumentNullException>(metadata != null);
  47. if (name.Contains("."))
  48. {
  49. throw new ArgumentException("'name' may not contain periods.");
  50. }
  51. _initialized = new Subject<AvaloniaPropertyChangedEventArgs>();
  52. _changed = new Subject<AvaloniaPropertyChangedEventArgs>();
  53. _metadata = new Dictionary<Type, PropertyMetadata>();
  54. Name = name;
  55. PropertyType = valueType;
  56. OwnerType = ownerType;
  57. Notifying = notifying;
  58. Id = s_nextId++;
  59. _metadata.Add(ownerType, metadata);
  60. _defaultMetadata = metadata;
  61. }
  62. /// <summary>
  63. /// Initializes a new instance of the <see cref="AvaloniaProperty"/> class.
  64. /// </summary>
  65. /// <param name="source">The direct property to copy.</param>
  66. /// <param name="ownerType">The new owner type.</param>
  67. /// <param name="metadata">Optional overridden metadata.</param>
  68. protected AvaloniaProperty(
  69. AvaloniaProperty source,
  70. Type ownerType,
  71. PropertyMetadata metadata)
  72. {
  73. Contract.Requires<ArgumentNullException>(source != null);
  74. Contract.Requires<ArgumentNullException>(ownerType != null);
  75. _initialized = source._initialized;
  76. _changed = source._changed;
  77. _metadata = new Dictionary<Type, PropertyMetadata>();
  78. Name = source.Name;
  79. PropertyType = source.PropertyType;
  80. OwnerType = ownerType;
  81. Notifying = source.Notifying;
  82. Id = source.Id;
  83. _defaultMetadata = source._defaultMetadata;
  84. // Properties that have different owner can't use fast path for metadata.
  85. _hasMetadataOverrides = true;
  86. if (metadata != null)
  87. {
  88. _metadata.Add(ownerType, metadata);
  89. }
  90. }
  91. /// <summary>
  92. /// Gets the name of the property.
  93. /// </summary>
  94. public string Name { get; }
  95. /// <summary>
  96. /// Gets the type of the property's value.
  97. /// </summary>
  98. public Type PropertyType { get; }
  99. /// <summary>
  100. /// Gets the type of the class that registered the property.
  101. /// </summary>
  102. public Type OwnerType { get; }
  103. /// <summary>
  104. /// Gets a value indicating whether the property inherits its value.
  105. /// </summary>
  106. public virtual bool Inherits => false;
  107. /// <summary>
  108. /// Gets a value indicating whether this is an attached property.
  109. /// </summary>
  110. public virtual bool IsAttached => false;
  111. /// <summary>
  112. /// Gets a value indicating whether this is a direct property.
  113. /// </summary>
  114. public virtual bool IsDirect => false;
  115. /// <summary>
  116. /// Gets a value indicating whether this is a readonly property.
  117. /// </summary>
  118. public virtual bool IsReadOnly => false;
  119. /// <summary>
  120. /// Gets an observable that is fired when this property is initialized on a
  121. /// new <see cref="AvaloniaObject"/> instance.
  122. /// </summary>
  123. /// <remarks>
  124. /// This observable is fired each time a new <see cref="AvaloniaObject"/> is constructed
  125. /// for all properties registered on the object's type. The default value of the property
  126. /// for the object is passed in the args' NewValue (OldValue will always be
  127. /// <see cref="UnsetValue"/>.
  128. /// </remarks>
  129. /// <value>
  130. /// An observable that is fired when this property is initialized on a new
  131. /// <see cref="AvaloniaObject"/> instance.
  132. /// </value>
  133. public IObservable<AvaloniaPropertyChangedEventArgs> Initialized => _initialized;
  134. /// <summary>
  135. /// Gets an observable that is fired when this property changes on any
  136. /// <see cref="AvaloniaObject"/> instance.
  137. /// </summary>
  138. /// <value>
  139. /// An observable that is fired when this property changes on any
  140. /// <see cref="AvaloniaObject"/> instance.
  141. /// </value>
  142. public IObservable<AvaloniaPropertyChangedEventArgs> Changed => _changed;
  143. /// <summary>
  144. /// Gets a method that gets called before and after the property starts being notified on an
  145. /// object.
  146. /// </summary>
  147. /// <remarks>
  148. /// When a property changes, change notifications are sent to all property subscribers;
  149. /// for example via the <see cref="AvaloniaProperty.Changed"/> observable and and the
  150. /// <see cref="AvaloniaObject.PropertyChanged"/> event. If this callback is set for a property,
  151. /// then it will be called before and after these notifications take place. The bool argument
  152. /// will be true before the property change notifications are sent and false afterwards. This
  153. /// callback is intended to support Control.IsDataContextChanging.
  154. /// </remarks>
  155. public Action<IAvaloniaObject, bool> Notifying { get; }
  156. /// <summary>
  157. /// Gets the integer ID that represents this property.
  158. /// </summary>
  159. internal int Id { get; }
  160. internal bool HasChangedSubscriptions => _changed?.HasObservers ?? false;
  161. /// <summary>
  162. /// Provides access to a property's binding via the <see cref="AvaloniaObject"/>
  163. /// indexer.
  164. /// </summary>
  165. /// <param name="property">The property.</param>
  166. /// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
  167. public static IndexerDescriptor operator !(AvaloniaProperty property)
  168. {
  169. return new IndexerDescriptor
  170. {
  171. Priority = BindingPriority.LocalValue,
  172. Property = property,
  173. };
  174. }
  175. /// <summary>
  176. /// Provides access to a property's template binding via the <see cref="AvaloniaObject"/>
  177. /// indexer.
  178. /// </summary>
  179. /// <param name="property">The property.</param>
  180. /// <returns>A <see cref="IndexerDescriptor"/> describing the binding.</returns>
  181. public static IndexerDescriptor operator ~(AvaloniaProperty property)
  182. {
  183. return new IndexerDescriptor
  184. {
  185. Priority = BindingPriority.TemplatedParent,
  186. Property = property,
  187. };
  188. }
  189. /// <summary>
  190. /// Tests two <see cref="AvaloniaProperty"/>s for equality.
  191. /// </summary>
  192. /// <param name="a">The first property.</param>
  193. /// <param name="b">The second property.</param>
  194. /// <returns>True if the properties are equal, otherwise false.</returns>
  195. public static bool operator ==(AvaloniaProperty a, AvaloniaProperty b)
  196. {
  197. if (object.ReferenceEquals(a, b))
  198. {
  199. return true;
  200. }
  201. else if (((object)a == null) || ((object)b == null))
  202. {
  203. return false;
  204. }
  205. else
  206. {
  207. return a.Equals(b);
  208. }
  209. }
  210. /// <summary>
  211. /// Tests two <see cref="AvaloniaProperty"/>s for inequality.
  212. /// </summary>
  213. /// <param name="a">The first property.</param>
  214. /// <param name="b">The second property.</param>
  215. /// <returns>True if the properties are equal, otherwise false.</returns>
  216. public static bool operator !=(AvaloniaProperty a, AvaloniaProperty b)
  217. {
  218. return !(a == b);
  219. }
  220. /// <summary>
  221. /// Registers a <see cref="AvaloniaProperty"/>.
  222. /// </summary>
  223. /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
  224. /// <typeparam name="TValue">The type of the property's value.</typeparam>
  225. /// <param name="name">The name of the property.</param>
  226. /// <param name="defaultValue">The default value of the property.</param>
  227. /// <param name="inherits">Whether the property inherits its value.</param>
  228. /// <param name="defaultBindingMode">The default binding mode for the property.</param>
  229. /// <param name="notifying">
  230. /// A method that gets called before and after the property starts being notified on an
  231. /// object; the bool argument will be true before and false afterwards. This callback is
  232. /// intended to support IsDataContextChanging.
  233. /// </param>
  234. /// <returns>A <see cref="StyledProperty{TValue}"/></returns>
  235. public static StyledProperty<TValue> Register<TOwner, TValue>(
  236. string name,
  237. TValue defaultValue = default(TValue),
  238. bool inherits = false,
  239. BindingMode defaultBindingMode = BindingMode.OneWay,
  240. Action<IAvaloniaObject, bool> notifying = null)
  241. where TOwner : IAvaloniaObject
  242. {
  243. Contract.Requires<ArgumentNullException>(name != null);
  244. var metadata = new StyledPropertyMetadata<TValue>(
  245. defaultValue,
  246. defaultBindingMode: defaultBindingMode);
  247. var result = new StyledProperty<TValue>(
  248. name,
  249. typeof(TOwner),
  250. metadata,
  251. inherits,
  252. notifying);
  253. AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
  254. return result;
  255. }
  256. /// <summary>
  257. /// Registers an attached <see cref="AvaloniaProperty"/>.
  258. /// </summary>
  259. /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
  260. /// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
  261. /// <typeparam name="TValue">The type of the property's value.</typeparam>
  262. /// <param name="name">The name of the property.</param>
  263. /// <param name="defaultValue">The default value of the property.</param>
  264. /// <param name="inherits">Whether the property inherits its value.</param>
  265. /// <param name="defaultBindingMode">The default binding mode for the property.</param>
  266. /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
  267. public static AttachedProperty<TValue> RegisterAttached<TOwner, THost, TValue>(
  268. string name,
  269. TValue defaultValue = default(TValue),
  270. bool inherits = false,
  271. BindingMode defaultBindingMode = BindingMode.OneWay,
  272. Func<THost, TValue, TValue> validate = null)
  273. where THost : IAvaloniaObject
  274. {
  275. Contract.Requires<ArgumentNullException>(name != null);
  276. var metadata = new StyledPropertyMetadata<TValue>(
  277. defaultValue,
  278. defaultBindingMode: defaultBindingMode);
  279. var result = new AttachedProperty<TValue>(name, typeof(TOwner), metadata, inherits);
  280. var registry = AvaloniaPropertyRegistry.Instance;
  281. registry.Register(typeof(TOwner), result);
  282. registry.RegisterAttached(typeof(THost), result);
  283. return result;
  284. }
  285. /// <summary>
  286. /// Registers an attached <see cref="AvaloniaProperty"/>.
  287. /// </summary>
  288. /// <typeparam name="THost">The type of the class that the property is to be registered on.</typeparam>
  289. /// <typeparam name="TValue">The type of the property's value.</typeparam>
  290. /// <param name="name">The name of the property.</param>
  291. /// <param name="ownerType">The type of the class that is registering the property.</param>
  292. /// <param name="defaultValue">The default value of the property.</param>
  293. /// <param name="inherits">Whether the property inherits its value.</param>
  294. /// <param name="defaultBindingMode">The default binding mode for the property.</param>
  295. /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
  296. public static AttachedProperty<TValue> RegisterAttached<THost, TValue>(
  297. string name,
  298. Type ownerType,
  299. TValue defaultValue = default(TValue),
  300. bool inherits = false,
  301. BindingMode defaultBindingMode = BindingMode.OneWay,
  302. Func<THost, TValue, TValue> validate = null)
  303. where THost : IAvaloniaObject
  304. {
  305. Contract.Requires<ArgumentNullException>(name != null);
  306. var metadata = new StyledPropertyMetadata<TValue>(
  307. defaultValue,
  308. defaultBindingMode: defaultBindingMode);
  309. var result = new AttachedProperty<TValue>(name, ownerType, metadata, inherits);
  310. var registry = AvaloniaPropertyRegistry.Instance;
  311. registry.Register(ownerType, result);
  312. registry.RegisterAttached(typeof(THost), result);
  313. return result;
  314. }
  315. /// <summary>
  316. /// Registers a direct <see cref="AvaloniaProperty"/>.
  317. /// </summary>
  318. /// <typeparam name="TOwner">The type of the class that is registering the property.</typeparam>
  319. /// <typeparam name="TValue">The type of the property's value.</typeparam>
  320. /// <param name="name">The name of the property.</param>
  321. /// <param name="getter">Gets the current value of the property.</param>
  322. /// <param name="setter">Sets the value of the property.</param>
  323. /// <param name="unsetValue">The value to use when the property is cleared.</param>
  324. /// <param name="defaultBindingMode">The default binding mode for the property.</param>
  325. /// <param name="enableDataValidation">
  326. /// Whether the property is interested in data validation.
  327. /// </param>
  328. /// <returns>A <see cref="AvaloniaProperty{TValue}"/></returns>
  329. public static DirectProperty<TOwner, TValue> RegisterDirect<TOwner, TValue>(
  330. string name,
  331. Func<TOwner, TValue> getter,
  332. Action<TOwner, TValue> setter = null,
  333. TValue unsetValue = default(TValue),
  334. BindingMode defaultBindingMode = BindingMode.OneWay,
  335. bool enableDataValidation = false)
  336. where TOwner : IAvaloniaObject
  337. {
  338. Contract.Requires<ArgumentNullException>(name != null);
  339. Contract.Requires<ArgumentNullException>(getter != null);
  340. var metadata = new DirectPropertyMetadata<TValue>(
  341. unsetValue: unsetValue,
  342. defaultBindingMode: defaultBindingMode);
  343. var result = new DirectProperty<TOwner, TValue>(
  344. name,
  345. getter,
  346. setter,
  347. metadata,
  348. enableDataValidation);
  349. AvaloniaPropertyRegistry.Instance.Register(typeof(TOwner), result);
  350. return result;
  351. }
  352. /// <summary>
  353. /// Returns a binding accessor that can be passed to <see cref="AvaloniaObject"/>'s []
  354. /// operator to initiate a binding.
  355. /// </summary>
  356. /// <returns>A <see cref="IndexerDescriptor"/>.</returns>
  357. /// <remarks>
  358. /// The ! and ~ operators are short forms of this.
  359. /// </remarks>
  360. public IndexerDescriptor Bind()
  361. {
  362. return new IndexerDescriptor
  363. {
  364. Property = this,
  365. };
  366. }
  367. /// <inheritdoc/>
  368. public override bool Equals(object obj)
  369. {
  370. var p = obj as AvaloniaProperty;
  371. return p != null && Equals(p);
  372. }
  373. /// <inheritdoc/>
  374. public bool Equals(AvaloniaProperty other)
  375. {
  376. return other != null && Id == other.Id;
  377. }
  378. /// <inheritdoc/>
  379. public override int GetHashCode()
  380. {
  381. return Id;
  382. }
  383. /// <summary>
  384. /// Gets the property metadata for the specified type.
  385. /// </summary>
  386. /// <typeparam name="T">The type.</typeparam>
  387. /// <returns>
  388. /// The property metadata.
  389. /// </returns>
  390. public PropertyMetadata GetMetadata<T>() where T : IAvaloniaObject
  391. {
  392. return GetMetadata(typeof(T));
  393. }
  394. /// <summary>
  395. /// Gets the property metadata for the specified type.
  396. /// </summary>
  397. /// <param name="type">The type.</param>
  398. /// <returns>
  399. /// The property metadata.
  400. /// </returns>
  401. ///
  402. public PropertyMetadata GetMetadata(Type type)
  403. {
  404. if (!_hasMetadataOverrides)
  405. {
  406. return _defaultMetadata;
  407. }
  408. return GetMetadataWithOverrides(type);
  409. }
  410. /// <summary>
  411. /// Checks whether the <paramref name="value"/> is valid for the property.
  412. /// </summary>
  413. /// <param name="value">The value.</param>
  414. /// <returns>True if the value is valid, otherwise false.</returns>
  415. public bool IsValidValue(object value)
  416. {
  417. return TypeUtilities.TryConvertImplicit(PropertyType, value, out value);
  418. }
  419. /// <summary>
  420. /// Gets the string representation of the property.
  421. /// </summary>
  422. /// <returns>The property's string representation.</returns>
  423. public override string ToString()
  424. {
  425. return Name;
  426. }
  427. /// <summary>
  428. /// True if <see cref="Initialized"/> has any observers.
  429. /// </summary>
  430. internal bool HasNotifyInitializedObservers => _initialized.HasObservers;
  431. /// <summary>
  432. /// Notifies the <see cref="Initialized"/> observable.
  433. /// </summary>
  434. /// <param name="o">The object being initialized.</param>
  435. internal abstract void NotifyInitialized(IAvaloniaObject o);
  436. /// <summary>
  437. /// Notifies the <see cref="Initialized"/> observable.
  438. /// </summary>
  439. /// <param name="e">The observable arguments.</param>
  440. internal void NotifyInitialized(AvaloniaPropertyChangedEventArgs e)
  441. {
  442. _initialized.OnNext(e);
  443. }
  444. /// <summary>
  445. /// Notifies the <see cref="Changed"/> observable.
  446. /// </summary>
  447. /// <param name="e">The observable arguments.</param>
  448. internal void NotifyChanged(AvaloniaPropertyChangedEventArgs e)
  449. {
  450. _changed.OnNext(e);
  451. }
  452. /// <summary>
  453. /// Routes an untyped ClearValue call to a typed call.
  454. /// </summary>
  455. /// <param name="o">The object instance.</param>
  456. internal abstract void RouteClearValue(IAvaloniaObject o);
  457. /// <summary>
  458. /// Routes an untyped GetValue call to a typed call.
  459. /// </summary>
  460. /// <param name="o">The object instance.</param>
  461. internal abstract object RouteGetValue(IAvaloniaObject o);
  462. /// <summary>
  463. /// Routes an untyped SetValue call to a typed call.
  464. /// </summary>
  465. /// <param name="o">The object instance.</param>
  466. /// <param name="value">The value.</param>
  467. /// <param name="priority">The priority.</param>
  468. internal abstract void RouteSetValue(
  469. IAvaloniaObject o,
  470. object value,
  471. BindingPriority priority);
  472. /// <summary>
  473. /// Routes an untyped Bind call to a typed call.
  474. /// </summary>
  475. /// <param name="o">The object instance.</param>
  476. /// <param name="source">The binding source.</param>
  477. /// <param name="priority">The priority.</param>
  478. internal abstract IDisposable RouteBind(
  479. IAvaloniaObject o,
  480. IObservable<BindingValue<object>> source,
  481. BindingPriority priority);
  482. internal abstract void RouteInheritanceParentChanged(AvaloniaObject o, IAvaloniaObject oldParent);
  483. /// <summary>
  484. /// Overrides the metadata for the property on the specified type.
  485. /// </summary>
  486. /// <param name="type">The type.</param>
  487. /// <param name="metadata">The metadata.</param>
  488. protected void OverrideMetadata(Type type, PropertyMetadata metadata)
  489. {
  490. Contract.Requires<ArgumentNullException>(type != null);
  491. Contract.Requires<ArgumentNullException>(metadata != null);
  492. if (_metadata.ContainsKey(type))
  493. {
  494. throw new InvalidOperationException(
  495. $"Metadata is already set for {Name} on {type}.");
  496. }
  497. var baseMetadata = GetMetadata(type);
  498. metadata.Merge(baseMetadata, this);
  499. _metadata.Add(type, metadata);
  500. _metadataCache.Clear();
  501. _hasMetadataOverrides = true;
  502. }
  503. private PropertyMetadata GetMetadataWithOverrides(Type type)
  504. {
  505. if (type is null)
  506. {
  507. throw new ArgumentNullException(nameof(type));
  508. }
  509. if (_metadataCache.TryGetValue(type, out PropertyMetadata result))
  510. {
  511. return result;
  512. }
  513. Type currentType = type;
  514. while (currentType != null)
  515. {
  516. if (_metadata.TryGetValue(currentType, out result))
  517. {
  518. _metadataCache[type] = result;
  519. return result;
  520. }
  521. currentType = currentType.GetTypeInfo().BaseType;
  522. }
  523. _metadataCache[type] = _defaultMetadata;
  524. return _defaultMetadata;
  525. }
  526. }
  527. /// <summary>
  528. /// Class representing the <see cref="AvaloniaProperty.UnsetValue"/>.
  529. /// </summary>
  530. public sealed class UnsetValueType
  531. {
  532. internal UnsetValueType() { }
  533. /// <summary>
  534. /// Returns the string representation of the <see cref="AvaloniaProperty.UnsetValue"/>.
  535. /// </summary>
  536. /// <returns>The string "(unset)".</returns>
  537. public override string ToString() => "(unset)";
  538. }
  539. }