// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Perspex.Data; namespace Perspex { /// /// A direct perspex property. /// /// The class that registered the property. /// The type of the property's value. /// /// Direct perspex properties are backed by a field on the object, but exposed via the /// system. They hold a getter and an optional setter which /// allows the perspex property system to read and write the current value. /// public class DirectProperty : PerspexProperty, IDirectPropertyAccessor where TOwner : IPerspexObject { /// /// Initializes a new instance of the class. /// /// The name of the property. /// Gets the current value of the property. /// Sets the value of the property. May be null. /// The property metadata. public DirectProperty( string name, Func getter, Action setter, PropertyMetadata metadata) : base(name, typeof(TOwner), metadata) { Contract.Requires(getter != null); Getter = getter; Setter = setter; } /// /// Initializes a new instance of the class. /// /// The property to copy. /// Gets the current value of the property. /// Sets the value of the property. May be null. /// Optional overridden metadata. private DirectProperty( PerspexProperty source, Func getter, Action setter, PropertyMetadata metadata) : base(source, typeof(TOwner), metadata) { Contract.Requires(getter != null); Getter = getter; Setter = setter; } /// public override bool IsDirect => true; /// public override bool IsReadOnly => Setter == null; /// /// Gets the getter function. /// public Func Getter { get; } /// /// Gets the setter function. /// public Action Setter { get; } /// /// Registers the direct property on another type. /// /// The type of the additional owner. /// Gets the current value of the property. /// Sets the value of the property. /// /// The value to use when the property is set to /// /// The default binding mode for the property. /// The property. public DirectProperty AddOwner( Func getter, Action setter = null, TValue unsetValue = default(TValue), BindingMode defaultBindingMode = BindingMode.OneWay) where TNewOwner : PerspexObject { var result = new DirectProperty( this, getter, setter, new DirectPropertyMetadata(unsetValue, defaultBindingMode)); PerspexPropertyRegistry.Instance.Register(typeof(TNewOwner), result); return result; } /// object IDirectPropertyAccessor.GetValue(IPerspexObject instance) { return Getter((TOwner)instance); } /// void IDirectPropertyAccessor.SetValue(IPerspexObject instance, object value) { if (Setter == null) { throw new ArgumentException($"The property {Name} is readonly."); } Setter((TOwner)instance, (TValue)value); } } }