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

WP开发 专栏收录该内容
4 篇文章 0 订阅

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 Members
    
    public event PropertyChangedEventHandler PropertyChanged;
    
    // Used to notify the page that a data context property changed
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    
    #endregion
    
    #region INotifyPropertyChanging Members
    
    public event PropertyChangingEventHandler PropertyChanging;
    
    // Used to notify the data context that a data context property is about to change
    private 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 database
    private 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();
        }
    }
    
    
    
    
注:以上代码来自网络,使用时需理解后灵活变通
  • 0
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值