![](/img/trans.png)
[英]Set Color for individual Treeview items based on data not bound to the treeview WPF
[英]WPF - Bound treeview not updating root items
我正在使用WPF TreeView控件,該控件已綁定到基於ObservableCollections的簡單樹結構。 這是XAML:
<TreeView Name="tree" Grid.Row="0">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
<TextBlock Text="{Binding Path=Text}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
和樹結構:
public class Node : IEnumerable {
private string text;
private ObservableCollection<Node> children;
public string Text { get { return text; } }
public ObservableCollection<Node> Children { get { return children; } }
public Node(string text, params string[] items){
this.text = text;
children = new ObservableCollection<Node>();
foreach (string item in items)
children.Add(new Node(item));
}
public IEnumerator GetEnumerator() {
for (int i = 0; i < children.Count; i++)
yield return children[i];
}
}
我將這棵樹的ItemsSource設置為我的樹結構的根,並且該樹的子項成為樹中的根級項(正如我想要的那樣):
private Node root;
root = new Node("Animals");
for(int i=0;i<3;i++)
root.Children.Add(new Node("Mammals", "Dogs", "Bears"));
tree.ItemsSource = root;
我可以將新的子代添加到樹結構的各個非根節點中,它們會正確顯示在TreeView中。
root.Children[0].Children.Add(new Node("Cats", "Lions", "Tigers"));
但是,如果我將一個孩子添加到根節點:
root.Children.Add(new Node("Lizards", "Skinks", "Geckos"));
該項目未出現,並且我嘗試過的所有操作(例如將ItemsSource設置為null,然后再次返回)均未導致該項目出現。
如果我在設置ItemsSource之前添加了蜥蜴,則它們會顯示出來,但是如果以后添加它們,則不會顯示。
有任何想法嗎?
您正在設置ItemsSource = root,它恰好實現IEnumerable,但本身並不可見。 即使您具有可觀察到的Children屬性,也不是將TreeView綁定到的屬性,因此TreeView沒有任何方法可以監聽通過Children屬性發生的更改。
我將從Node類中完全刪除IEnumerable。 然后設置treeView.ItemsSource = root.Children;
如果“ root”是ObservableCollection,則樹形視圖將更新。 “根”是可觀察的集合,還是“根”是可觀察的集合中的節點? 查看您對項目源的綁定將有助於回答此問題。 當您在代碼中分配它時,您可能只是將其設置為單個元素,而不是集合
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.