我意识到DataTemplate的普通用例是在XAML中声明它(无论是作为资源还是显式使用它),但是如果我可以在代码中创建模板(特别是C#),我的特定项目将会受益匪浅.而不是在XAML中.我遇到的问题是我的代码创建的DataTemplate使用FrameworkElementFactory作为模板的VisualTree,而XAML创建的模板使用TemplateContent对象作为模板的Template值.我现在可以告诉你,所讨论的网格控件适用于使用模板的模板,但似乎不能很好地使用使用VisualTree的模板.
通过比较,这里是XAML中的一个模板作为我的选择器的一部分:
<MySelectorType> <MySelectorType.BooleanTemplate> <DataTemplate> <EditorControl Name="Reserved_Name" /> </DataTemplate> </MySelectorType.BooleanTemplate> </MySelectorType>
var template = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(EditorControl)) { Name = "Reserved_Name" } };
我也试过这样:
var template = new DataTemplate() { VisualTree = new FrameworkElementFactory(typeof(EditorControl)) }; template.VisualTree.SetValue(EditorControl.NameProperty,"Reserved_Name");
这似乎更类似于XAML模板的功能,但似乎根本不起作用(编辑器既不读取也不设置值,至少第一个版本会读取它).
我的代码内模板是否可以使用Template属性而不是VisualTree?根据the documentation,这种类型没有公共API,实例化路径很复杂,但这已经完成了吗?我发现的唯一example在代码中使用了硬编码的XAML,这对我来说并不合适.
解决方法
FrameworkElementFactory
的文档中可以找到以下内容:
This class is a deprecated way to programmatically create templates,which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class.
我不知道在代码中使用Template属性的任何简单方法,我可能知道的唯一方法是通过大量反思.
设置名称是一种特殊情况,如果您设置了工厂的Name属性,它应该正确注册,如果不是,您需要手动获取approriate Namescope
和register名称.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。