Fomin Dmitry
Fomin Dmitry

Reputation: 51

How to create instance of control from DataTemplate in code behind

How can i create the instance of control described by DataTemplate in code behind? I found a template in resource dictionary:

var template = resourceDictionary["Button"] as DataTemplate;

Now i want to create a control by using DataTemplate, but how?

var control = template.[MakeControl]?

Upvotes: 2

Views: 699

Answers (1)

mm8
mm8

Reputation: 169200

Call LoadContent() and cast the result:

var template = resourceDictionary["Button"] as DataTemplate;
var control = template.LoadContent() as Button;

<DataTemplate x:Key="Button">
    <Button Content="btn" />
</DataTemplate>

Upvotes: 6

Related Questions