// -----------------------------------------------------------------------
//
// Copyright 2015 MIT Licence. See licence.md for more information.
//
// -----------------------------------------------------------------------
namespace Perspex.Controls.Templates
{
using System;
using System.Reflection;
///
/// Builds a control for a piece of data.
///
public class DataTemplate : FuncTemplate, IDataTemplate
{
///
/// The default data template used in the case where not matching data template is found.
///
public static readonly DataTemplate Default =
new DataTemplate(typeof(object), o => (o != null) ? new TextBlock { Text = o.ToString() } : null);
///
/// The implementation of the method.
///
private 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.
///
public DataTemplate(Type type, Func build)
: this(o => IsInstance(o, type), build)
{
}
///
/// 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.
///
public DataTemplate(Func match, Func build)
: base(build)
{
Contract.Requires(match != null);
this.match = match;
}
///
/// 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 this.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 (o != null) ?
t.GetTypeInfo().IsAssignableFrom(o.GetType().GetTypeInfo()) :
false;
}
}
}