【问题标题】:Access DataTemplate from ResourceDictionary when DataTemplate doesn't have a key, only TargetType当 DataTemplate 没有键,只有 TargetType 时从 ResourceDictionary 访问 DataTemplate
【发布时间】:2013-11-28 00:35:49
【问题描述】:

我在 XAML 中定义了一个带有代码隐藏的 ResouceDictionary。我需要使用鼠标事件和数据绑定定义一些特定于视图的行为,为此我需要访问在 DataTemplate 中定义的一些元素。

问题是,DataTemplate 没有 Key 它只有一个 TargetType(这是必需的,因此 WPF 会自动将其用于给定类型)。

那么,如何从代码隐藏中访问 DataTemplate?

编辑:

如果我在构造函数的某处放置断点,我可以看到我的 ViewModel 的模板就在那里。看来 ResourceDictionary.Keys 属性是一个对象数组,而我要访问的键(实际上是对应的值)在调试器中是这样的:

{DataTemplateKey(Company.Application.ViewModels.TargetViewModel)}

XAML:

<sys:Double x:Key="escala">10</sys:Double>
<sys:Double x:Key="raio">20</sys:Double>
<EllipseGeometry x:Key="geometriacirculo"
    RadiusX="{StaticResource raio}"
    RadiusY="{StaticResource raio}"/>
<ScaleTransform x:Key="transform" ScaleX="{StaticResource escala}" ScaleY="{StaticResource escala}" />
<ap:NormalConverter x:Key="NormalConverter"/>   
<ap:BitmapToSource x:Key="BitmapToSource"/>

<DataTemplate DataType="{x:Type vm:TelaColetaViewModel}">
        <.....

代码隐藏:

public partial class TelaColetaTemplate : ResourceDictionary
{

    EllipseGeometry _geometria_circulo;
    ScaleTransform _scale_transform;
    Grid GridZoom;
    Path CirculoGuia;

    double _escala;

    Point? _ponto_clicado_norm;     

    public TelaColetaTemplate()
    {
        InitializeComponent();

        // three following lines work, accessing them with key, no problem
        _geometria_circulo = (EllipseGeometry)this["geometriacirculo"];
        _scale_transform = (ScaleTransform)this["transform"];
        _escala = (double)this["escala"];


        //var wantedTemplate = ????

        ......

【问题讨论】:

  • 如果您使用x:Key,您可以使用静态方法FindResource。我不知道“无名”DataTemplates。对不起
  • @Tico 如果您希望它为给定类型自动加载(而不是显式加载),则不要将密钥放入 DataTemplate 中,这一点很重要。如果我放一个断点,我可以看到隐式键,只是不知道如何访问它,看我的编辑。
  • 当我使用DataTemplates时,它只与 XAML 一起使用,从来没有在代码后面使用过。但我确实使用上述方法申请资源。好问题,我会看这个帖子的。
  • 正如您在编辑中提到的,仅提及 DataType 但没有键的 DataTemplates 将为它们创建隐式键。因此,对于您的 DataTemplate,密钥将是 new DataTemplateKey(typeof(TargetViewModel))
  • @sthotakura 我非常感谢你,var wantedTemplate = this[new DataTemplateKey(typeof(TelaColetaViewModel))]; 简单的一行让我得到了我想要的。如果你把它放在一个答案中,我会接受它。

标签: wpf code-behind resourcedictionary targettype


【解决方案1】:

DataTemplates 只提到了DataType 但没有x:Key 将为它们创建一个隐式密钥。因此,基本上要访问您的 DataTemplate,您需要做的就是创建一个 DataTemplate 键并将其用作您的 ResourceDictionary 的索引器参数

示例代码如下:

new DataTemplateKey(typeof(TargetViewModel));

【讨论】:

  • 太棒了。真的希望找到使用 DataType 的数据模板。谢谢
  • 你是天才!这也适用于 xaml。 &lt;ContentControl ContentTemplate="{StaticResource {DataTemplateKey {x:Type local:MyType}}}"....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-21
  • 1970-01-01
  • 2012-10-26
相关资源
最近更新 更多