Mark A. Donohoe
Mark A. Donohoe

Reputation: 30368

How can I manually look up a DataTemplate defined only by DataType, not key?

I'm trying to get the DataTemplate that will be used for a specific type.

I was under the impression that when you only specified the DataType, it implicitly uses that value as the key for that resource so the system can go look it up.

I attempted to test that with this code...

MainWindow.wpf:

xmlns:system="clr-namespace:System;assembly=mscorlib"
<Window.Resources>
    <DataTemplate DataType="{x:Type system:String}">
        <Border x:Name="Bd"
            BorderBrush="Red" BorderThickness="1" CornerRadius="6"
            Padding="6,4">
            <TextBlock Text="{Binding}" />
        </Border>
    </DataTemplate>
</Window.Resources>

... then I attempted the following, which fails...

var stringType = typeof(string);
var stringDataTemplate = this.FindResource(stringType);

So how can I programmatically retrieve a data type defined only by type?

Upvotes: 2

Views: 218

Answers (1)

brunnerh
brunnerh

Reputation: 184441

The type is used as key for Styles, for DataTemplates you can construct a DataTemplateKey from the type.

(As with the DataType in XAML you can pass an object for XML templating by tag name. You have to pass a type for CLR classes.)

Upvotes: 3

Related Questions