c# - 将项目添加到底层 ObservableCollection 时,递归 TreeView 不保留结构

标签 c# wpf mvvm treeview

我正在使用此模型构建递归 WPF TreeView:

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

所以(名字不好)Category1 是子类别的集合,Category2 是父类别。如果后者位于树的顶层,则后者可以为空。

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>

Categories 是一个 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 下方的位置。在顶层(即 Category2Id 为 null 的项目)有与以前相同数量的项目。但是在 UI 中,这个新项目被渲染为好像它位于顶层而不是树中的正确位置。

起初,我想知道这是否是直接使用 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 interface任何更改...只需手动调用(您的接口(interface)方法的实现)...

NotifyPropertyChanged("Categories");

...在您的 AddCategory 末尾方法来提醒界面注意 Categories收藏发生了变化。

关于c# - 将项目添加到底层 ObservableCollection 时,递归 TreeView 不保留结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34023391/

相关文章:

c# - Controller MVC 中的全局变量

c# - 为什么在 QueryOver SingleOrDefault 中很慢?

c# - 违反通用参数约束?

c# - 如何在MVVM中组合异步和非异步服务?

java - 在 Android 中使用四向滑动的 RecyclerView

asp.net-mvc - MVVM 模式的核心是什么?

c# - 在没有源代码的情况下在 VS 中调试

c# - 如何从 RichTextBox 控件的撤消堆栈中删除操作?

c# - 在Messenger中注册方法时使用Action <T1,T2>

c# - 将两种形式作为不同的线程运行(或至少 2 种形式运行 "parallel")