这是我的项目树:
该项目是一个简单的图书经理。它与sqlite数据库进行交互。
YourBooks类如下:
public sealed partial class YourBooks : Page
{
private ObservableCollection<Book> Books;
public YourBooks()
{
this.InitializeComponent();
DatabaseManager.InitializeDatabase();
Books = DatabaseManager.GetBooks();
}
private async void Add_a_book_Clicked(object sender, RoutedEventArgs e)
{
//This doesn't matter
}
}
DatabaseManager类充当应用程序和数据库之间的中间人。这是代码:
class Book
{
public string Title { get; set; }
public string Author { get; set; }
public string ISBN { get; set; }
public int Quantity { get; set; }
public string CoverImage { get; set; }
}
class DatabaseManager
{
public static void InitializeDatabase()
{
using (SqliteConnection db = new SqliteConnection("FileName= MyBooks.db"))
{
db.Open();
string command = "create table if not exists MyBooks " +
"(title text primary key not null, author text not null, isbn text not null, quantity integer not null, " +
"CoverImage text not null)";
SqliteCommand createTable = new SqliteCommand(command, db);
SqliteDataReader reader = createTable.ExecuteReader();
while(reader.Read())
{ }
}
}
public static ObservableCollection<Book> GetBooks()
{
using (SqliteConnection db = new SqliteConnection("FileName=MyBooks.db"))
{
db.Open();
string command = "select title, author, quantity, CoverImage from MyBooks";
SqliteCommand getBooks = new SqliteCommand(command, db);
SqliteDataReader dataReturned = getBooks.ExecuteReader();
ObservableCollection<Book> books = new ObservableCollection<Book>();
while(dataReturned.Read())
{
books.Add(new Book
{
Title = dataReturned.GetString(0),
Author = dataReturned.GetString(1),
Quantity = dataReturned.GetInt32(2),
CoverImage = dataReturned.GetString(3)
});
}
return books;
}
}
public static void AddBook(string title, string author, string isbn, int quantity, string coverImageLocation)
{
using (SqliteConnection db = new SqliteConnection("FileName=MyBooks.db"))
{
db.Open();
SqliteCommand command = new SqliteCommand
{
CommandText = "insert into MyBooks values (@title, @author, @isbn, @quantity, @coverImage)",
Connection = db
};
command.Parameters.AddWithValue("@title", title);
command.Parameters.AddWithValue("@author", author);
command.Parameters.AddWithValue("@isbn", isbn);
command.Parameters.AddWithValue("@quantity", quantity);
command.Parameters.AddWithValue("@coverImage", coverImageLocation);
command.ExecuteReader();
}
}
}
在NewBooks类中,我这样更新数据库:
DatabaseManager.AddBook(BookNameTextBox.Text, AuthorTextBox.Text, ISBNTextBox.Text, Convert.ToInt32(Quantity.Text), destinationFile.Path);
我想通知YourBooks类数据库已更改。在UWP之前,我对Qt的了解很少。并且在Qt中它具有信号和时隙机制。因此,您要做的就是定义一个可以触发并调用该插槽的信号。
如何从NewBook通知YourBooks数据库已更改,以便它可以更新。
答案 0 :(得分:2)
在Book
类(或任何您调用的类型)中实现INotifyPropertyChanged接口,并在每次将其属性设置为新值时引发PropertyChanged
事件。
然后,视图中绑定到相应属性的任何UI元素都会自动更新。
如果将新书添加到数据库,则还应该向Book
绑定到的ObservableCollection<T>
添加新的GridView
对象。
在您的情况下,您可以从DatabaseManager
类中引发一个事件,并在YourBooks
类中对该事件进行处理。