如何创建依赖于XML属性数据模板? [英] How to create a data template dependent on an XML Attribute?
问题描述
我正在一个WPF界面,读取XML文件并显示数据上。 XML文件是这样的:
I'm working on a WPF interface that reads an XML file and displays the data. The XML file would be something like this:
<People>
<Person Gender="Male">
<Name>Joe</Name>
</Person>
<Person Gender="Female">
<Name>Susan</Name>
</Person>
</People>
我需要依赖于人的性别属性的数据模板。该数据模板是列表框中的项目。列表框的来源是人民。
I need a data template dependent on the Gender attribute of Person. This data template is for list box items. the source of the listbox is People.
<DataTemplate DataType="Person[@Gender='Male']">
</DataTemplate>
<DataTemplate DataType="Person[@Gender='Female']">
</DataTemplate>
我认为这会是这样的code以上线,但它不工作。任何想法?
I thought it would be something like the above line of code, but it doesn't work. Any ideas?
谢谢!
答
下面是上面的XML例子DataTemplateSelector:
ANSWER
Here's the DataTemplateSelector for the above XML example:
public class MyDataTemplateSelector : DataTemplateSelector
{
private DataTemplate _MaleTemplate = null;
private DataTemplate _FemaleTemplate = null;
public DataTemplate MaleTemplate
{
get { return _MaleTemplate; }
set { _MaleTemplate = value; }
}
public DataTemplate FemaleTemplate
{
get { return _FemaleTemplate; }
set { _FemaleTemplate = value; }
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
XmlElement currentNode = (XmlElement)item;
DataTemplate selectedTemplate = null;
string selectedGender = "";
selectedGender = currentNode.GetAttribute("Gender");
switch (selectedGender)
{
case "Male":
selectedTemplate = _MaleTemplate;
break;
case "Female":
selectedTemplate = _FemaleTemplate;
break;
default:
break;
}
return selectedTemplate;
}
}
感谢您的帮助!我希望这将是有用的人别人的!
Thanks for the help! I hope this will be useful to someone else as well!
推荐答案
您需要使用的 DataTemplateSelector 。通过WPF博士这文章完全演示了而正是你所期待的。
You need to use a DataTemplateSelector. This article by Dr. WPF demonstrates it completely and is just what you are looking for.
这篇关于如何创建依赖于XML属性数据模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!