这是我的项目树:
该项目是一个简单的图书管理器。它与 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 数据库已更改,以便它可以自行更新。
在您的类(或您调用的任何类型)中实现INotifyPropertyChanged接口,Book
并PropertyChanged
在将其属性设置为新值时引发该事件。
然后绑定到相应属性的视图中的任何 UI 元素将自动更新。
如果您向数据库中添加一本新书,您还应该向您所绑定的Book
对象添加一个新对象。ObservableCollection<T>
GridView
在您的情况下,您可以从DatabaseManager
类中引发一个事件并在类中处理该事件YourBooks
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句