ObservableCollection无法更新TreeView

时间:2018-07-12 12:37:04

标签: c# wpf xaml observablecollection

我不明白为什么我的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; } 
}

1 个答案:

答案 0 :(得分:0)

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