以前写的了,Silverlight用的人貌似不多。
主要是使用XmlReader读取XML的Attribute数据读取到TreeViewItem的Header和DataContext中,点击TreeView节点的时候将DataContext取出来。
读取XML核心代码:
private void LoadCameraListTree(TreeViewItem parentItem, XmlReader reader, int CurrentLevel)
{
CurrentLevel = CurrentLevel + 1;
//XmlReader的ReadSubtree不光是该节点的子节点,还包括该节点本身
//因此要跳过第一个节点
int i = 0;
while (reader.Read())
{
if (0 != i && reader.IsStartElement() && reader.HasAttributes)
{
TreeViewItem item = new TreeViewItem();
item.Header = reader.GetAttribute("name");
item.DataContext = CurrentLevel.ToString() + "&" + reader.GetAttribute("Id") + "&" + reader.GetAttribute("name");
parentItem.Items.Add(item);
LoadCameraListTree(item, reader.ReadSubtree(), CurrentLevel);
}
if (0 == i)
{
++i;
}
}
}
XmlReader reader = XmlReader.Create("demo.xml");
while (reader.Read())
{
if (reader.IsStartElement() && reader.GetAttribute("Id") == "1")
{
int CurrentLevel = 1;
TreeViewItem item = new TreeViewItem();
item.Header = reader.GetAttribute("name");
item.DataContext = CurrentLevel.ToString() + "&" + reader.GetAttribute("Id") + "&" + reader.GetAttribute("name");
treeView_XML.Items.Add(item);
LoadCameraListTree(item, reader.ReadSubtree(), CurrentLevel);
}
}
private void treeView_XML_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
TreeView view = sender as TreeView;
TreeViewItem SelectedItem = (TreeViewItem)view.SelectedItem;
string SelectedItem_DataContext = (string)SelectedItem.DataContext;
textBlock_Debug.Text = SelectedItem_DataContext;
string[] SelectedItem_Attributes = SelectedItem_DataContext.Split("&".ToCharArray());
string SelectedItem_Level = SelectedItem_Attributes[0];
textBox_Level.Text = SelectedItem_Level;
textBox_Id.Text = SelectedItem_Attributes[1];
textBox_name.Text = SelectedItem_Attributes[2];
}
完整代码可以从下面的链接下载:
http://download.csdn.net/detail/chenxupro/6351375
运行效果如下: