我认为这很简单,但找不到任何好的例子。
public Class BookVm : ImplementsPropertyChanged
{
public int BookId {get;set;}
private bool _favorite;
public bool Favorite
{
get { return _favorite; }
set {
_favorite = value;
OnPropertyChanged("Favorite");
MyDbContext.SaveChanges() // this does not work
}
}
然后在我的XAML绑定到Book
<CheckBox Content="Favorite" IsChecked="{Binding Favorite}" />
我如何以及何时在DatabaseContext上调用SaveChanges()?
我不想实现保存按钮。如果我拦截PropertyChange事件并调用SaveChanges,似乎什么也没发生。我的对象在内存中被修改,但数据库没有看到更改。
我的BookVm
类是在应用程序启动时创建的,如下所示:
foreach (var book in MyDbContext.Books)
Books.Add(book);
我的Books
ObservableCollection<Book>
是MainWindowVm
的位置
答案 0 :(得分:1)
假设您有一个dataservice类,它返回book并更新一本书:
public class DataService
{
public static void UpdateBook(Book book)
{
//Call the context to update the database
}
public static IEnumerable<Book> FetchBooks()
{
// return DBContext.GetBooks
}
}
现在您可以创建一个View Model,它可以获取一本书然后返回属性。 BookId不会按照数据库进行更改(如果它是主键)。
//Domain Object
public class Book
{
public int BookId { get; set; }
public bool Favourite { get; set; }
}
//View Model
public class BookVm : ImplementsPropertyChanged
{
private readonly Book book;
//Store the book
public BookVm(Book book)
{
this.book = book;
}
private bool favorite;
public int BookId
{
get { return book.BookId; }
}
public bool Favorite
{
get { return favorite; }
set
{
if (favorite != value)
{
favorite = value;
//Update the database
UpdateDatabase();
}
}
}
private void UpdateDatabase()
{
//set the favorite value of the domain book
book.Favourite = favorite;
DataService.UpdateBook(book);
}
}
我们将域对象存储在ViewModel中供以后用户使用。 我们还可以编写一个控制器来显示如下视图:
public class BookController
{
public void Display()
{
IEnumerable<Book> books = DataService.FetchBooks();
ObservableCollection<BookVm> bookVms = new ObservableCollection<BookVm>();
foreach (var book in books)
{
BookVm bookVm = new BookVm(book);
bookVms.Add(bookVm);
}
//Get the View and then bind using the bookVms collection
}
}
答案 1 :(得分:0)
答案 2 :(得分:0)
还猜测您在Implements属性更改中有类似的代码。
public class ImplementsPropertyChanged : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
您还需要添加以下内容以引发通知。
public bool Favorite
{
get { return favorite; }
set
{
if (favorite != value)
{
favorite = value;
//Update the database
UpdateDatabase();
OnPropertyChanged("Favorite");
}
}
}