AvaloniaProperty.cs 23 KB

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