Uso DataTemplate.LoadContent(). Ejemplo:
DataTemplate dataTemplate = this.Resources["MyDataTemplate"] as DataTemplate;
FrameworkElement frameworkElement = dataTemplate.LoadContent() as FrameworkElement;
frameworkElement.DataContext = myPOCOInstance;
LayoutRoot.Children.Add(frameworkElement);
http://msdn.microsoft.com/en-us/library/system.windows.frameworktemplate.loadcontent.aspx
Si usted tiene un DataTemplate definido para todas las instancias de un tipo (Tipo de datos = {x: Tipo ...}, pero no x: Key = "...") luego puede crear contenido utilizando la DataTemplate apropiada utilizando el siguiente método estático. Este método también emula ContentControl devolviendo un TextBlock si no se encuentra DataTemplate.
/// <summary>
/// Create content for an object based on a DataType scoped DataTemplate
/// </summary>
/// <param name="sourceObject">Object to create the content from</param>
/// <param name="resourceDictionary">ResourceDictionary to search for the DataTemplate</param>
/// <returns>Returns the root element of the content</returns>
public static FrameworkElement CreateFrameworkElementFromObject(object sourceObject, ResourceDictionary resourceDictionary)
{
// Find a DataTemplate defined for the DataType
DataTemplate dataTemplate = resourceDictionary[new DataTemplateKey(sourceObject.GetType())] as DataTemplate;
if (dataTemplate != null)
{
// Load the content for the DataTemplate
FrameworkElement frameworkElement = dataTemplate.LoadContent() as FrameworkElement;
// Set the DataContext of the loaded content to the supplied object
frameworkElement.DataContext = sourceObject;
// Return the content
return frameworkElement;
}
// Return a TextBlock if no DataTemplate is found for the source object data type
TextBlock textBlock = new TextBlock();
Binding binding = new Binding(String.Empty);
binding.Source = sourceObject;
textBlock.SetBinding(TextBlock.TextProperty, binding);
return textBlock;
}
Quiero algo que haga exactamente lo que hace la clase Contenido. es decir, sigue la misma lógica que el control de contenido en sí. Tu código es bueno y estaría bien para el escenario de DataTemplate. Pero puede que no haya definido una DataTemplate para mi POCO. –
Si no hay ningún DataTemplate coincidente, volverá a crear un TextBlock y usar ToString() en el objeto POCO para definir el texto. –
bastante fácil, me acaba de actualizar el método para crear un cuadro de texto en lugar de devolver un valor nulo si no se encuentra ninguna DataTemplate. FYI - ContentControl muestra contenido UIElement como UIElement, así que no se utilice este método si ya tiene un UIElement como contenido. –