I have a StudentsViewModel
class that contains an ObservableCollection<Student>
property called StudentsList
. The StudentsList is bound to a DataGrid
in my StudentsView
. When I add a new student using the AddStudentCommand
, the new student is added to the database successfully, but the StudentsList
in the view is not updating immediately. I have to navigate away from the view and then come back to see the updated list.
I have verified that the AddStudent
method is correctly adding the new student to the database and also adding it to the StudentsList
collection. However, the view does not reflect the changes right away. I believe there might be an issue with how the StudentsList is being updated or bound to the view.
I have shared the relevant code snippets below:
StudentsViewModel.cs
public class StudentsViewModel : ObservableObject
{
DriveBuddyEntities _db;
private ObservableCollection<Student> _studentsList;
public ObservableCollection<Student> StudentsList
{
get { return _studentsList; }
set
{
_studentsList = value;
OnPropertyChanged(nameof(StudentsList));
}
}
private Student _newStudent = new Student();
public Student NewStudent
{
get => _newStudent;
set
{
_newStudent = value;
OnPropertyChanged(nameof(NewStudent));
}
}
private string _newStudentSelectedCourseCategory;
public string NewStudentSelectedCourseCategory
{
get => _newStudentSelectedCourseCategory;
set
{
_newStudentSelectedCourseCategory = value;
OnPropertyChanged(nameof(NewStudentSelectedCourseCategory));
}
}
public ICommand AddStudentCommand { get; set; }
public StudentsViewModel()
{
_db = new DriveBuddyEntities();
LoadStudents();
AddStudentCommand = new RelayCommand(AddStudent);
}
private void LoadStudents() => StudentsList = new ObservableCollection<Student>(_db.Students);
private void AddStudent(object obj)
{
try
{
CourseDetail courseDetail = _db.CourseDetails.FirstOrDefault(cd => cd.Category.CategoryName == NewStudentSelectedCourseCategory);
if (courseDetail != null)
{
NewStudent.CourseDetails.Add(courseDetail);
_db.Students.Add(NewStudent);
_db.SaveChanges();
MessageBox.Show("Student has been created", "Message", MessageBoxButton.OK, MessageBoxImage.Information);
StudentsList.Add(NewStudent);
NewStudent = new Student();
}
else
{
MessageBox.Show("Invalid course category", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch
{
MessageBox.Show("Something went wrong. Student has not been created. Check your data.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
StudentsView.xaml
<!--#region ===== DataGrid ===== -->
<DataGrid Grid.Row="1" Margin="10"
RowStyle="{DynamicResource DataGridRowStyle}"
ColumnHeaderStyle="{DynamicResource DataGridColumnHeaderStyle}"
CellStyle="{DynamicResource DataGridCellStyle}"
Style="{DynamicResource DataGridStyle}"
ItemsSource="{Binding StudentsList}">
<DataGrid.Columns>
....
</DataGrid.Columns>
</DataGrid>
<!--#endregion-->