Search code examples
wpfcode-behindresourcedictionarytargettype

Access DataTemplate from ResourceDictionary when DataTemplate doesn't have a key, only TargetType


I have a ResouceDictionary defined in XAML with codebehind. I need to define some view-specific behaviors with mouse-events and databinding, and for that I need to access some elements defined inside a DataTemplate.

The problem is, the DataTemplate doesn't have a Key it only has a TargetType (that is needed so WPF will automatically use it for the given type).

So, how can I access the DataTemplate from codebehind?

EDIT:

If I put a breakpoint somewhere in the constructor, I can see that the template for my ViewModel is there. It seems that ResourceDictionary.Keys property is an array of objects, and the key I want to access (or the corresponding value, actually) is like this in the debugger:

{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}">
        <.....

CodeBehind:

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 = ????

        ......

Solution

  • DataTemplates with just DataType mentioned but no x:Key will have an implicit key created for them. So, essentially to get to your DataTemplate, all you need to do is Create a DataTemplate Key and use it an indexer parameter for your ResourceDictionary

    Sample Code below:

    new DataTemplateKey(typeof(TargetViewModel));