簡體   English   中英

將項目添加到基礎ObservableCollection時,遞歸TreeView不會保留結構

[英]Recursive TreeView does not retain structure when items added to underlying ObservableCollection

我正在使用此模型構建遞歸WPF TreeView:

public class Category
{
    public virtual ICollection<Category> Category1 { get; set; }
    public virtual Category Category2 { get; set; }
}

因此(不好稱)Category1是子類別的集合,而Category2是父類別。 如果后者在樹的頂層,則后者可以為null。

TreeView的呈現方式如下:

<TreeView ItemsSource="{Binding Categories}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Category1}">
            <Button Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ViewContentsCommand}" 
                CommandParameter="{Binding}" Width="100" HorizontalAlignment="Stretch">
                <TextBlock FontWeight="Bold"  Text="{Binding Name}"></TextBlock>
            </Button>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

類別是一個ObservableCollection,因此當用戶通過UI從集合中添加或刪除集合中的項目時,它應該更新。 在顯示方面,這一切都按預期進行。

我不知道當用戶將一個項目添加到集合中時會發生什么。 這是代碼:

public void AddCategory()
{
    Category c = new Category { Description = "New Category",  Category2Id = SelectedCategory.CategoryId };
    Categories.Add(c);
    OnPropertyChanged("Categories"); //to refresh the UI
}

如果您在此處放置一個斷點並檢查Categories集合,則按預期進行-新項目已插入其應分配的ParentId下方的樹中。 在頂層(即,類別2Id為空的項目)的項目數量與以前相同。 但是,在用戶界面中,此新項目的呈現方式就好像位於頂層,而不是樹中的正確位置一樣。

起初,我想知道這是否是直接使用ObservableCollection的特性,所以我嘗試了以下方法:

public void AddCategory()
{
    List<Category> cats = Categories.ToList();
    Category c = new Category { Description = "New Category",  Category2Id = SelectedCategory.CategoryId };
    cats.Add(c);
    Categories = cats.ToObservableCollection();
}

我本來希望沒有任何作用,但是令我驚訝的是,什么也沒有發生,也就是說,新類別根本沒有出現在UI中。

我究竟做錯了什么?

在集合上調用Add方法將不會向INotifyPropertyChanged接口發出任何更改的警報...只是手動調用(您對接口方法的實現)...

NotifyPropertyChanged("Categories");

...在您的AddCategory方法的末尾,以警告界面有關Categories集合已更改的事實。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM