简体   繁体   English

如何创建已定义为资源的Xaml DataTemplate的新实例?

[英]How do I create a new instance of a Xaml DataTemplate that has been defined as a resource?

I need to dynamically generate a DataTemplate that is defined as a resource. 我需要动态生成一个定义为资源的DataTemplate。 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. 动态生成DataTemplate的示例**是**,但不生成现有模板的实例。

Example of a derived UserControl that contains a DataTemplate by the name of "template" that I want to create a new instance of. 派生的UserControl的示例,该示例包含要创建其新实例的“模板”名称的DataTemplate。

<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. 我的回答如下。

Surprisingly the answer came by fully reading the DateTemplate class documentation! 出乎意料的是,通过完整阅读DateTemplate类文档可以找到答案! Cast the resource as a DataTemplate and call LoadContent() on it! 将资源转换为DataTemplate并在其上调用LoadContent()!

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" );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM