// 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.Reactive.Linq; namespace Avalonia.Controls.Templates { /// /// Builds a control for a piece of data. /// public class FuncDataTemplate : FuncTemplate, IDataTemplate { /// /// The default data template used in the case where no matching data template is found. /// public static readonly FuncDataTemplate Default = new FuncDataTemplate( (data, s) => { if (data != null) { var result = new TextBlock(); result.Bind( TextBlock.TextProperty, result.GetObservable(Control.DataContextProperty).Select(x => x?.ToString())); return result; } else { return null; } }, true); /// /// The implementation of the method. /// private readonly Func _match; /// /// Initializes a new instance of the class. /// /// The type of data which the data template matches. /// /// A function which when passed an object of returns a control. /// /// Whether the control can be recycled. public FuncDataTemplate( Type type, Func build, bool supportsRecycling = false) : this(o => IsInstance(o, type), build, supportsRecycling) { } /// /// Initializes a new instance of the class. /// /// /// A function which determines whether the data template matches the specified data. /// /// /// A function which returns a control for matching data. /// /// Whether the control can be recycled. public FuncDataTemplate( Func match, Func build, bool supportsRecycling = false) : base(build) { Contract.Requires(match != null); _match = match; SupportsRecycling = supportsRecycling; } /// public bool SupportsRecycling { get; } /// /// Checks to see if this data template matches the specified data. /// /// The data. /// /// True if the data template can build a control for the data, otherwise false. /// public bool Match(object data) { return _match(data); } /// /// Determines of an object is of the specified type. /// /// The object. /// The type. /// /// True if is of type , otherwise false. /// private static bool IsInstance(object o, Type t) { return t.IsInstanceOfType(o); } } }