管理 [WPF]如何使用代码创建DataTemplate(或者ControlTemplate)

 

1. 前言#

上一篇文章([UWP]如何使用代码创建DataTemplate(或者ControlTemplate))介绍了在UWP上的情况,这篇文章再稍微介绍在WPF上如何实现。

2. 使用FrameworkElementFactory#

FrameworkElementFactory用于以编程的方式创建模板,虽然文档中说不推荐,但WPF中常常使用这个类,例如DisplayMemberTemplateSelector

Copy
FrameworkElementFactory text = new FrameworkElementFactory(typeof(TextBlock)); Binding binding = new Binding { Path = new PropertyPath("Name") }; text.SetBinding(TextBlock.TextProperty, binding); var xmlNodeContentTemplate = new DataTemplate(); xmlNodeContentTemplate.VisualTree = text; xmlNodeContentTemplate.Seal(); ListControl.ItemTemplate = xmlNodeContentTemplate;

使用方式如上,这种方式可以方便地使用代码设置绑定或属性值,并且提供了AppendChild方法用于创建复杂的树结构。但是一旦这样做将使代码变得很复杂,建议还是不要这样做。

3. 使用XamlReader和XamlWriter#

和UWP一样,WPF也支持使用XamlReader构建模板,只不过需要将

Copy
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

改为

Copy
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

和UWP不一样的是WPF还有XamlWriter这个工具。

XamlWriter提供一个静态 Save 方法,该方法可用于以受限的 XAML 序列化方式,将所提供的运行时对象序列化为 XAML 标记。如果使用这个类说不定可以用普通的方式创建一个UI元素并且最终创建它对应的DataTemplate,例如这样:

Copy
TextBlock text = new TextBlock(); Binding binding = new Binding("Name"); text.SetBinding(TextBlock.TextProperty, binding); string xaml = string.Empty; using (var stream = new MemoryStream()) { XamlWriter.Save(text, stream); using (var streamReader = new StreamReader(stream)) { stream.Seek(0, SeekOrigin.Begin); xaml = streamReader.ReadToEnd(); } } var template = (DataTemplate)XamlReader.Parse(@" <DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml""> " + xaml + @" </DataTemplate>");

但现实没有这么简单,在生成xaml的那步就出错了,声称的xaml如下:

Copy
<TextBlock Text="" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" />

可以看到这段XAML并没有反映text.SetBinding(TextBlock.TextProperty, binding);这段设置的绑定。具体原因可见

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信