如何以编程方式访问DataTemplate的关联dataType?

时间:2014-12-10 23:42:20

标签: c# wpf resources datatemplate

我有:

<DataTemplate DataType="{x:Type svgEdit:UserControlSvgEditModel}">
        <svgEdit:UserControlSvgEdit />
</DataTemplate>

我想以编程方式获取类型:svgEdit:UserControlSvgEdit

我做:

        // Here the obj Type is the key to the resource, it works but
        var key = new System.Windows.DataTemplateKey(obj.GetType());
        var dataTemplate = (DataTemplate)DockSite.FindResource(key);
        // I don't know how to get the DataTemplate associated type ????
        var tc = dataTemplate.Template as TemplateContent;

但我找不到如何检索相关类型?

注意:我需要以编程方式实例化模板内容并将其传递给DockSite(Docking Manager)

1 个答案:

答案 0 :(得分:4)

DataTemplate.LoadContent()方法将给出DataTemplate.Using中的根元素,我们可以获取模板内容的数据类型。修改后的代码将如下所示,

        var key = new System.Windows.DataTemplateKey(typeof(ProductsViewModel));
        var dataTemplate = (DataTemplate)this.FindResource(key);

        var tc = dataTemplate.LoadContent().GetType();
        var instance = Activator.CreateInstance(tc);