我试图弄清楚如何将 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.CooperativeViewModel” - 例如,它没有用于显示视图的模板。

有帮助吗?

解决方案

为了使其正确工作,这里的关键是使用 数据模板键:

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

如果您这样做,它应该按指定的方式工作。但是,那 框架元素工厂 根据文档,“一种已弃用的以编程方式创建模板的方法”,因此您可能需要直接解析 XAML。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top