DataGrid的ItemsSource更改后如何自动刷新?

How to refresh DataGrid's ItemsSource automatically after changed?

我不明白为什么我的 ItemsSource 没有自动改变,但是当再次调用持有 DataGriddialog 时,它改变了。

这是我的 ViewModel:

public ObservableCollection<Student> Students { get; set; } = new ObservableCollection<Student>();


private RelayCommand<ObservableCollection<Student>> _getStudents;

//this is my list getter 
public RelayCommand<ObservableCollection<Student>> GetStudents
{
    get
    {
        return _getStudents
        ?? (_getStudents= new RelayCommand<ObservableCollection<Student>>(DoGetStudents));
    }
}

public void DoGetStudents(ObservableCollection<Student> students)
{
    Students = new ObservableCollection<Student>();

    var studs = _myService.GetStudents();

    foreach (var item in studs)
    {
        Students.Add(item);
    }
}


// adding function but not auto refresh
private async void DoAddStudent()
{
    await _myService.AddStudent(Student);
    DoGetStudents.Execute(null);
}

尽管在添加后调用了 DoGetStudents.Execute(null); 行,但对话框中的 DataGrid 不会刷新,除非我重新打开对话框。我可能缺少什么?

如果您将 属性 设置为新的 ObservableCollection<Student>,您还应该实施 INotifyPropertyChanged 并从 setter 引发 PropertyChanged 事件=14=].

但是您可以重复使用同一个集合并在命令执行时清除它,而不是这样做:

public void DoGetStudents(ObservableCollection<Student> students)
{
    Students.Clear();

    var studs = _myService.GetStudents();

    foreach (var item in studs)
    {
        Students.Add(item);
    }
}

否则,你根本就不需要 ObservableCollection<T>