如何创建已定义为资源的 Xaml 数据模板的新实例
本文关键字:Xaml 数据 新实例 实例 何创建 创建 定义 资源 | 更新日期: 2023-09-27 18:32:38
我需要动态生成一个定义为资源的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>
我的回答如下。
令人惊讶的是,答案来自完全阅读 DateTemplate 类文档!将资源转换为数据模板并在其上调用 LoadContent()!
object template;
if( !imageView.Resources.TryGetValue( "template", out template ) ) {
var root = ((DataTemplate) template).LoadContent() as ScrollViewer;
imageView.ViewBox.Child = root;
}
或作为扩展方法:
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;
}
调用该方法:
var scrollViewer = userControl.GenerateDataTemplateInstance<ScrollViewer>( "template" );