创建使用本地数据库的WP7应用程序

来源:互联网 发布:cnc编程招聘 编辑:程序博客网 时间:2024/06/05 16:34

wp7支持本地数据库了,如下是创建使用本地数据库应用程序的基本方法:

第一步:构建数据上下文

  1. 添加引用:System.Data.Linq,并在程序中要用到的地方添加如下代码:
    using System.Data.Linq;using System.Data.Linq.Mapping;using System.ComponentModel;using System.Collections.ObjectModel;
  2. 添加数据表实体类:
    [Table]public class ToDoItem : INotifyPropertyChanged, INotifyPropertyChanging{// Define ID: private field, public property and database column.private int _toDoItemId;[Column(IsPrimaryKey = true, IsDbGenerated = true, DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)]public int ToDoItemId{    get    {        return _toDoItemId;    }    set    {        if (_toDoItemId != value)        {            NotifyPropertyChanging("ToDoItemId");            _toDoItemId = value;            NotifyPropertyChanged("ToDoItemId");        }    }}// Define item name: private field, public property and database column.private string _itemName;[Column]public string ItemName{    get    {        return _itemName;    }    set    {        if (_itemName != value)        {            NotifyPropertyChanging("ItemName");            _itemName = value;            NotifyPropertyChanged("ItemName");        }    }}// Define completion value: private field, public property and database column.private bool _isComplete;[Column]public bool IsComplete{    get    {        return _isComplete;    }    set    {        if (_isComplete != value)        {            NotifyPropertyChanging("IsComplete");            _isComplete = value;            NotifyPropertyChanged("IsComplete");        }    }}// Version column aids update performance.[Column(IsVersion = true)]private Binary _version;#region INotifyPropertyChanged Memberspublic event PropertyChangedEventHandler PropertyChanged;// Used to notify the page that a data context property changedprivate void NotifyPropertyChanged(string propertyName){    if (PropertyChanged != null)    {        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));    }}#endregion#region INotifyPropertyChanging Memberspublic event PropertyChangingEventHandler PropertyChanging;// Used to notify the data context that a data context property is about to changeprivate void NotifyPropertyChanging(string propertyName){    if (PropertyChanging != null)    {        PropertyChanging(this, new PropertyChangingEventArgs(propertyName));    }}#endregion}
  3. 数据上下文类:
    public class ToDoDataContext : DataContext{    // Specify the connection string as a static, used in main page and app.xaml.    public static string DBConnectionString = "Data Source=isostore:/ToDo.sdf";    // Pass the connection string to the base class.    public ToDoDataContext(string connectionString)        : base(connectionString)    { }    // Specify a single table for the to-do items.    public Table<ToDoItem> ToDoItems;}


第二部:创建数据库

  1. 在App类构造函数末尾添加代码,如果数据库不存在则创建:
    // Create the database if it does not exist.using (ToDoDataContext db = new ToDoDataContext(ToDoDataContext.DBConnectionString)){    if (db.DatabaseExists() == false)    {        //Create the database        db.CreateDatabase();    }}
  2. 为了支持数据绑定,使相应的类实现INotifyPropertyChanged接口:
    public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged{    // Constructor    public MainPage()    {        InitializeComponent();    }    #region INotifyPropertyChanged Members    public event PropertyChangedEventHandler PropertyChanged;    // Used to notify Silverlight that a property has changed.    private void NotifyPropertyChanged(string propertyName)    {        if (PropertyChanged != null)        {            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));        }    }    #endregion}
  3. 在相应类构造函数里声明一个DataContext,如下代码:
    // Data context for the local databaseprivate ToDoDataContext toDoDB;// Define an observable collection property that controls can bind to.private ObservableCollection<ToDoItem> _toDoItems;public ObservableCollection<ToDoItem> ToDoItems{    get    {        return _toDoItems;    }    set    {        if (_toDoItems != value)        {            _toDoItems = value;            NotifyPropertyChanged("ToDoItems");        }    }}
  4. 在构造函数末尾添加如下代码:
    // Connect to the database and instantiate data context.toDoDB = new ToDoDataContext(ToDoDataContext.DBConnectionString);            // Data context and observable collection are children of the main page.this.DataContext = this;
  5. 重写函数在页面加载前从数据库获取信息:
    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e){// Define the query to gather all of the to-do items.var toDoItemsInDB = from ToDoItem todo in toDoDB.ToDoItems                    select todo;// Execute the query and place the results into a collection.ToDoItems = new ObservableCollection<ToDoItem>(toDoItemsInDB);                // Call the base method.    base.OnNavigatedTo(e);}
  6. 重写函数以便在页面变成非活动状态时做数据的保存工作: 
    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e){    // Call the base method.    base.OnNavigatedFrom(e);    // Save changes to the database.    toDoDB.SubmitChanges();}
  7. 数据添加:
    private void newToDoAddButton_Click(object sender, RoutedEventArgs e){    // Create a new to-do item based on the text box.    ToDoItem newToDo = new ToDoItem { ItemName = newToDoTextBox.Text };    // Add a to-do item to the observable collection.    ToDoItems.Add(newToDo);                // Add a to-do item to the local database.    toDoDB.ToDoItems.InsertOnSubmit(newToDo);          }

  8. 数据删除:
    private void deleteTaskButton_Click(object sender, RoutedEventArgs e){    // Cast parameter as a button.    var button = sender as Button;    if (button != null)    {        // Get a handle for the to-do item bound to the button.        ToDoItem toDoForDelete = button.DataContext as ToDoItem;        // Remove the to-do item from the observable collection.        ToDoItems.Remove(toDoForDelete);        // Remove the to-do item from the local database.        toDoDB.ToDoItems.DeleteOnSubmit(toDoForDelete);        // Save changes to the database.        toDoDB.SubmitChanges();        // Put the focus back to the main page.        this.Focus();    }}
注:以上代码来自网络,使用时需理解后灵活变通
原创粉丝点击