Reputation: 1847
I need to dynamically generate a DataTemplate that is defined as a resource. A seemingly simple task that I found answered nowhere, simply or otherwise. Examples of dynamically generating a DataTemplate ** yes ** but not generating instances of an existing template.
Example of a derived UserControl that contains a DataTemplate by the name of "template" that I want to create a new instance of.
<utilities:UserControlBase x:Class="Photomete.ImageView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Photomete"
xmlns:utilities="using:Utilities"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewModels="using:Photomete"
xmlns:cm="using:Caliburn.Micro"
xmlns:ia="clr-namespace:Microsoft.Xaml.Interactions.Core;assembly=Microsoft.Xaml.Interactions.dll"
mc:Ignorable="d"
FontSize="6"
d:DesignHeight="300"
d:DesignWidth="400">
<utilities:UserControlBase.Resources>
<DataTemplate x:Name="template">
<ScrollViewer x:Name="imageScroller"
VerticalScrollBarVisibility="Visible"
RenderTransformOrigin="0.5,0.5"
HorizontalScrollBarVisibility="Visible">
<Image x:Name="image"
Source="{Binding Source}" />
</ScrollViewer>
</DataTemplate>
</utilities:UserControlBase.Resources>
<Viewbox x:Name="viewBox">
<!-- Content is set in code behind -->
</Viewbox>
My answer follows.
Upvotes: 1
Views: 276
Reputation: 1847
Surprisingly the answer came by fully reading the DateTemplate class documentation! Cast the resource as a DataTemplate and call LoadContent() on it!
object template;
if( !imageView.Resources.TryGetValue( "template", out template ) ) {
var root = ((DataTemplate) template).LoadContent() as ScrollViewer;
imageView.ViewBox.Child = root;
}
or as an extension method:
public static T GenerateDataTemplateInstance<T>( this FrameworkElement element, string name ) where T : class
{
// ******
object template;
if( ! element.Resources.TryGetValue( name, out template ) ) {
return null;
}
// ******
return ((DataTemplate) template).LoadContent() as T;
}
calling the method:
var scrollViewer = userControl.GenerateDataTemplateInstance<ScrollViewer>( "template" );
Upvotes: 1