我在我的測驗專案中使用以下 ViewModel。我試圖遵循 MVVM 模式。我需要視圖中的即時更新功能。
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));
}
}
}
問題是當我向資料庫添加一個條目時,它不會更新,ListView并且只有在我重新運行應用程式時才能看到更改。第二個問題是,當我將游標焦點從選定的文本框上移開時,屬性會發生變化。是否可以在填充屬性時更改屬性?
uj5u.com熱心網友回復:
如另一個答案所示,不需要重新加載整個集合。將單個專案添加到當前集合中:
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);
}
uj5u.com熱心網友回復:
您在 studentList 中缺少 OnPropertyChanged:
public ObservableCollection<Student> studentList
{
get
{
return _studentList;
}
set
{
_studentList = value;
OnPropertyChanged(“studentList”);
}
}
編輯:
插入資料時需要再次加載串列:
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);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/448349.html
