首页 > 解决方案 > ObservableCollection 不更新 TreeView

问题描述

我不明白为什么我的 TreeView 不使用 ObservableCollection 更新。

主窗口

 public ObservableCollection<Student> listStudents { get; set; }



    internal MainWindow(List<Student> list, Controller controller)
    {         
        this.listStudents = new ObservableCollection<Student>(list);
        this.controller = controller;

        InitializeComponent();
        this.DataContext = this;
    }

XAML

 <TreeView x:Name="tv_source" AllowDrop="True" Grid.Row="2" Grid.Column="1" Margin="0,5" HorizontalAlignment="Stretch" ItemsSource="{Binding ListStudents}" Background="White" BorderBrush="{x:Null}">

我添加一个这样的孩子:

public void addChild(TreeViewItem _sourceItem, TreeViewItem _targetItem)
        {
            Dispatcher.BeginInvoke(new Action(() => ((Student)_targetItem.DataContext).Phones.Add(_sourceItem.DataContext.ToString())));
        }

学生班

public class Student
{ 
    public string Name { get; set; }

    public List<string> Phones { get; set; } 
}

标签: c#wpfxamlobservablecollection

解决方案


如果要将字符串添加到Phones属性并针对此集合绑定数据,则应将其类型更改ObservableCollection<string>为添加string以显示在 UI 中。现在好像是一个List<string>


推荐阅读