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>
I thought it would be something like the above line of code, but it doesn't work. Any ideas?
Thanks!
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!