I use the following ViewModel in my test project. I've tried to follow MVVM pattern. I need instant update feature in the view.
public class StudentListViewModel : INotifyPropertyChanged
{
private string _name;
private string _lastName;
private int _age;
private ObservableCollection<Student> _studentList;
public string Name
{
get => _name;
set
{
_name = value;
OnPropertyChanged("Name");
InsertCommand.RaiseCanExecuteChanged();
}
}
public string LastName
{
get => _lastName;
set
{
_lastName = value;
OnPropertyChanged("LastName");
InsertCommand.RaiseCanExecuteChanged();
}
}
public int Age
{
get => _age;
set
{
_age = value;
OnPropertyChanged("Age");
InsertCommand.RaiseCanExecuteChanged();
}
}
public RelayCommand InsertCommand { get; }
public StudentListViewModel()
{
InsertCommand = new RelayCommand((s) => InsertStudent(),
() => !string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(LastName) && Age > 0);
using (MyContext context = new MyContext())
{
studentList = new ObservableCollection<Student>(context.Students);
};
}
public void InsertStudent()
{
Student st = new Student()
{
Name = Name,
LastName = LastName,
Age = Age
};
using (var context = new MyContext())
{
context.Add(st);
context.SaveChanges();
}
}
public ObservableCollection<Student> studentList
{
get
{
return _studentList;
}
set
{
_studentList = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The problem is that when I add an entry to the database, it does not update the ListView
and the change is only seen when I rerun the app. The second problem is that property is changed when I leave the cursor focus away from the selected textbox. Is it possible to change property as you fill the property?
CodePudding user response:
there is not need to reload entire collection as shown in the other answer. add single item into the current collection:
public void InsertStudent()
{
var st = new Student()
{
Name = Name,
LastName = LastName,
Age = Age
};
using (var context = new MyContext())
{
context.Add(st);
context.SaveChanges();
}
studentList.Add(st);
}
CodePudding user response:
You are missing OnPropertyChanged in studentList:
public ObservableCollection<Student> studentList
{
get
{
return _studentList;
}
set
{
_studentList = value;
OnPropertyChanged(“studentList”);
}
}
EDIT:
You need to load the list again when insert a data:
public void InsertStudent()
{
Student st = new Student()
{
Name = Name,
LastName = LastName,
Age = Age
};
using (var context = new MyContext())
{
context.Add(st);
context.SaveChanges();
studentList = new ObservableCollection<Student>(context.Students);
}
}