在代码中将 DataTemplate(非 XAML)添加到资源字典中?
-
21-09-2019 - |
题
我试图弄清楚如何将 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” - 例如,它没有用于显示视图的模板。
不隶属于 StackOverflow