【问题标题】:How to create instance of control from DataTemplate in code behind如何在后面的代码中从 DataTemplate 创建控件实例
【发布时间】:2019-05-05 16:43:07
【问题描述】:
如何在后面的代码中创建DataTemplate 描述的控件实例?我在资源字典中找到了一个模板:
var template = resourceDictionary["Button"] as DataTemplate;
现在我想使用DataTemplate 创建一个控件,但是如何?
var control = template.[MakeControl]?
【问题讨论】:
标签:
c#
.net
wpf
datatemplate
code-behind
【解决方案1】:
调用LoadContent() 并转换结果:
var template = resourceDictionary["Button"] as DataTemplate;
var control = template.LoadContent() as Button;
<DataTemplate x:Key="Button">
<Button Content="btn" />
</DataTemplate>