Search code examples
wpfmvvmmvvm-light

How to refresh DataGrid's ItemsSource automatically after changed?


I don't understand why my ItemsSource don't auto change but when the dialog that is holding the DataGrid is called again, it changed.

This is my 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);
}

Eventhough DoGetStudents.Execute(null); line got called after adding, the DataGrid in the dialog don't refresh unless I reopen the dialog. What could I be missing?


Solution

  • If you set the property to a new ObservableCollection<Student>, you should also implement INotifyPropertyChanged and raise the PropertyChanged event from the setter of Students.

    But instead of doing this, you can reuse the same collection and just clear it when the command executes:

    public void DoGetStudents(ObservableCollection<Student> students)
    {
        Students.Clear();
    
        var studs = _myService.GetStudents();
    
        foreach (var item in studs)
        {
            Students.Add(item);
        }
    }
    

    Otherwise, you don't really need an ObservableCollection<T> in the first place.