// -----------------------------------------------------------------------
//
// Copyright 2015 MIT Licence. See licence.md for more information.
//
// -----------------------------------------------------------------------
namespace Perspex.Controls.Templates
{
using System.Linq;
using Perspex.LogicalTree;
using Splat;
///
/// Defines extension methods for working with s.
///
public static class DataTemplateExtensions
{
///
/// Materializes a piece of data based on a data template.
///
/// The control materializing the data template.
/// The data.
/// The data materialized as a control.
public static IControl MaterializeDataTemplate(this IControl control, object data)
{
IDataTemplate template = control.FindDataTemplate(data);
IControl result;
if (template != null)
{
result = template.Build(data);
if (result != null && result.DataContext == null)
{
result.DataContext = data;
}
}
else if (data is IControl)
{
result = (IControl)data;
}
else
{
result = DataTemplate.Default.Build(data);
}
return result;
}
///
/// Find a data template that matches a piece of data.
///
/// The control searching for the data template.
/// The data.
/// The data template or null if no matching data template was found.
public static IDataTemplate FindDataTemplate(this IControl control, object data)
{
foreach (var i in control.GetSelfAndLogicalAncestors().OfType())
{
foreach (IDataTemplate dt in i.DataTemplates.Reverse())
{
if (dt.Match(data))
{
return dt;
}
}
}
IGlobalDataTemplates global = Locator.Current.GetService();
if (global != null)
{
foreach (IDataTemplate dt in global.DataTemplates.Reverse())
{
if (dt.Match(data))
{
return dt;
}
}
}
return null;
}
}
}