如何在代码隐藏中从 DataTemplate 创建控件实例

How to create instance of control from DataTemplate in code behind

如何在隐藏代码中创建 DataTemplate 描述的控件实例?我在资源词典中找到了一个模板:

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

现在我想使用 DataTemplate 创建一个控件,但是怎么做呢?

var control = template.[MakeControl]?

调用LoadContent()并转换结果:

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

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