Search code examples
c#.netwpfdatatemplatecode-behind

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

Solution

  • 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>