在代码中将DataTemplate(非XAML)添加到资源字典?

4

我正在尝试弄清楚如何将DataTemplate添加到应用程序的资源字典中。当DataTemplate在XAML中(通过uri)时,我知道如何做到这一点,但是当DataTemplate在代码中定义时,我有点困惑。

以下是我目前的代码,但并不起作用-

        //Create DataTemplate
        DataTemplate template = new DataTemplate(typeof(CoordinateViewModel));
        FrameworkElementFactory ViewStack = new FrameworkElementFactory(typeof(CoordinateView));
        ViewStack.Name = "myViewStack";

        template.VisualTree = ViewStack;


        ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.BeginInit();
        dictionary.Add(template, template);
        dictionary.EndInit();

        App.Current.Resources.MergedDictionaries.Add(dictionary);

编辑:尽管没有出现任何错误,但我尽力了解到DataTemplate并没有进入应用程序的资源字典中。当后来从XAML调用ViewModel时,它表现得好像没有正确的DataTemplate来显示它。例如,
<StackPanel>
    <ContentPresenter Content="{Binding ViewModel}" />
</StackPanel>

结果是一个空白窗口,显示了文本“ShellPrototype.ViewModels.CoordinateViewModel”- 例如,它没有模板来显示视图。


你能说一下具体出了什么问题吗?是抛出了异常吗?还是从字典中无法检索到值?(您尝试从字典中获取的方式是怎样的?)您能够从字典中获取到某个值,但它并不是您所期望的吗? - itowlson
是的,抱歉我之前讲得比较简略。我已经更新了帖子。简而言之,无法从字典中检索到DataTemplate。 - user237263
1个回答

2

要正确使其工作,关键是使用DataTemplateKey

ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Add(new DataTemplateKey(typeof(CoordinateViewModel)), template);

如果您这样做,它应该按照指定的方式工作。然而,根据文档,FrameworkElementFactory是“一种已弃用的以编程方式创建模板的方法”,因此您可能希望直接解析XAML。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接