数据模板适用于Content Control类控件与Items Control类控件.
我们假设有如下一个类










































这个类很简单地表示了一个人,他的姓名和他的照片(路径)
如果在我们的软件中有一个列表控件ListBox来显示一个由多个人组成的列表,在.net 3.0以前我们可能就只能用文本来列出人的姓名而已,或者花不少的精力来重写列表控件以便在列表中在显示人名的同时显示照片.
参考以下代码:

我们定义了一个ListBox,并将其ItemTemplate制定为我们自定义的MyTemplate,也就是说列表项将按照MyTemplate制定的方式来显示列表内容。
这样我们就可以发挥我们的想像力来自定义MyTemplate
为了能在XAML中使用我们的People类,我们需要将其名字空间引入,参考以下代码:

其中Demo是我们的People类所在的名字空间,以后可以使用demo来表示这个名字空间了.
下面的代码来定义我们的MyTemplate模板,以便告诉我们的列表如何来显示他的项目:













我们将模板定义为窗口的资源,资源保存在一个资源字典中的,x:Key=”MyTemplate” 表示其在资源字典中的键,DataType=”{x:Type demo:People}”表示该数据模板针对的数据类型是demo名字空间下的People类,接下来在Gird中我们定义了该数据模板的视觉树,这也是我们的工作重心,即该视觉树定义了如何显示我们的数据。我们使用了一个Image控件并将其Source绑定到People的Photo属性上,这样以便在该Imag控件上显示照片,然后在Image的右边我们使用一个TextBlock控件来显示人名(将People的Name属性绑定到TextBlock的Text属性上)。
注意到这个数据模板实际上在干什么:它定义了People类型对象的表现方式,在这里是显示People的照片并在照片的右方显示姓名。
以后我们需要People对象按这种方式展示给用户的时候,我们只要将该数据模板指定给要显示People对象的那个控件就可以了。
比如

就告诉我们的列表控件按照MyTemplate定义的方式来显示其项目。
转自:https://www.cnblogs.com/zhouyinhui/archive/2007/03/30/694388.html