2
我有一個TreeView如下:HierarchicalDataTemplate的TreeView - ContainerFromItem返回樹型視圖只針對第一項
<TreeView
Loaded="tv_Loaded_1"
DockPanel.Dock="Bottom"
Name="tv"
ItemsSource="{Binding XPath=*}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate
ItemsSource="{Binding XPath=*}">
<StackPanel
Orientation="Horizontal">
<TextBlock
Text="{Binding Name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
在後面的代碼中,我使用下面的XML作爲的DataContext:
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<a><b><c></c><d></d></b><e><f></f><g></g></e></a>");
DataContext = doc;
TreeView的是生成罰款,但枚舉的項目,我得到TreeViewItem只爲第一個XmlNode(根節點,即<a>
)和層次結構中剩下的XmlNodes沒有任何相應的TreeViewItems存在。
private IEnumerable<TreeViewItem> Enumerate(ItemCollection items)
{
foreach (XmlElement element in items)
{
TreeViewItem item = tv.ItemContainerGenerator.ContainerFromItem(element) as TreeViewItem;
if (item != null) //When second call with <a>.Items, item is null
{
yield return item;
}
//Enumerate is called again with <a>.Items
//Exception in second call, because item is null
foreach (TreeViewItem i in Enumerate(item.Items))
{
yield return i;
}
}
}
private void tv_Loaded_1(object sender, RoutedEventArgs e)
{
var list = Enumerate(tv.Items).ToList();
}
爲什麼樹中其餘的XmlNodes沒有任何TreeViewItem存在?
任何幫助,非常感謝。
非常感謝。我會試試這個。 – teenup