我正在尝试弄清楚如何将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”- 例如,它没有模板来显示视图。