IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    WP8.1开发:MVVM记事本-SQLite存储

    编程小梦发表于 2014-10-19 12:33:03
    love 0

    (正式开篇之前,先吐槽几句.小梦这周运气挺背的:

    • 首先是网站在12号晚莫名崩溃.从晚上8点一直搞到凌晨2点才搞定.这真是一行代码引发的血案,查找到原因后真心无比郁闷!
    • 其次是<随机信号分析>突然宣布平时要多加俩次考试,考试不过也直接挂科.再加上之前我们副院长带的双语课(英文课本,英文作业,英文课件,英文考试,就是讲课用下汉语)<数字信号处理>同样要多考俩次,本没有期中考试的大三就多了俩门考试.你说都在期末一次搞定是多么好啊.
    • 最后就是周五莫名发烧39.4.今天才差不多恢复!所以大家一定要多多锻炼身体哦!)

    小梦的感悟就是意外随时有可能降临,所以其实我们现在正常的学习,生活,工作已是一种幸福.我们应该去珍惜我们现在所拥有的一切,对于身边的人,事,物.我们应常怀感恩之心去对待他们.或许,明天,这一切都没有了呢?!不要以为你所拥有或得到的一切是理所应当的.

    下面我们正式开始,我们实现的是一个可以增删改查的记事本应用.有了这个基础,大家可以根据我前面介绍的图片选取保存,录音,Onedrive备份,人人网,新浪微博第三方分享等再进行扩展,这些我之前都讲过.

    首先我们需要安装SQLite数据库:

    请参考:

    • WP8.1SQLITE数据库安装详解
    • WP8.1SQLITE数据库基本操作

    记事本的service:

    Service就是实现对记事的增加,删除,更新,查找所有记事,查找指定ID记事.同时我们使用了单例模式.

    所谓单例模式就是:保证一个类仅有一个实例,并提供一个它的全局访问点.完整代码如下:

    using Note.Model;
    using SQLite;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Storage;
    using Windows.UI.Popups;
    
    namespace Note.Service
    {
       public  class DataService
        {
    
           private static DataService _dataService;//单例模式()
    
           public static DataService Current
           {
               get
               {
                   if (_dataService == null)
                   {
                       _dataService = new DataService();
                   }
                   return _dataService;
               }
           }
    
           private DataService()
           {
    
           }
    
           public static SQLiteAsyncConnection GetConn()//获取数据库
           {
               return new SQLiteAsyncConnection(ApplicationData.Current.LocalFolder.Path + "\\note.db");
           }
    
          public async void Add(Notes note)//增加记事
           {
               SQLiteAsyncConnection conn = GetConn();
               await conn.InsertAsync(note);
           }
    
           public async void Delete(int id)//删除记事
           {
               SQLiteAsyncConnection conn = GetConn();
               var query = from note in conn.Table()
                           where note.ID == id
                           select note;
               Notes notes = await query.FirstOrDefaultAsync();
               await conn.DeleteAsync(notes);
           }
    
           public async void  Modify(Notes notedemo)//更新记事
           {
               SQLiteAsyncConnection conn = GetConn();
               await conn.UpdateAsync(notedemo); 
           }
    
           public async Task Query(int id)//按ID查找记事
           {
               SQLiteAsyncConnection conn = GetConn();
               var query = from note in conn.Table()
                                   where note.ID == id
                                   select note;
               Notes notes = await query.FirstOrDefaultAsync();
               return notes;
           }
    
           public  async Task> Query()//查找所有记事
           {
               SQLiteAsyncConnection conn = GetConn();
    
               var query = conn.Table();
    
               List result = await query.ToListAsync();
               return result;
    
           }
       }
    }

     记事本的Model:

    Model就是对记事本数据的抽象.代码如下:

    using SQLite;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Note.Model
    {
        public class Notes:ModelBase
        {
    
            private int id;
            [AutoIncrement, PrimaryKey] //主键并且自增
            public int ID
            {
                get;
                set;
            }
    
            private string name;
            [MaxLength(1000)]
            public string Name
            {
                get { return name; }
                set
                { this.SetProperty(ref this.name, value); }
            }
    
            private string content;
            [MaxLength(3000)]
            public string Content
            {
                get { return content; }
                set
                { this.SetProperty(ref this.content,value); }
            }
        }
    }

    ModelBase类就是对INotifyPropertyChanged接口的具体实现,前面已经说过多次,这次就不贴代码了.

    记事本的View:

    一个最简单的记事本应用,我们至少需要俩个页面.一个用来显示所有记事,一个用来增加,修改记事.

    记事列表页:

    
            
                
                    
                        
                            
                                
                               
                              
                             
                            
                        
                                
                                
                        
                        
                    
                
            
        
        
            
                
            
        

    我们使用了MenuFlyout控件,不熟悉的朋友可以参考MSDN文档.用法很简单.

    增加.修改记事页:

    
            
                
            
             
            
            
            
        
        
            
                
                
            
        

     记事本的VIewModel

    有俩个View,同样我们也有俩个ViewModel:

    列表页的ViewModel:

    using Note.Command;
    using Note.Commons;
    using Note.Model;
    using Note.Service;
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Note.ViewModel
    {
        public class NoteListViewModel : ModelBase
        {
            private ObservableCollection notelist;
            public ObservableCollection Notelist
            {
                get
                {
                    return notelist;
                }
                set
                { this.SetProperty(ref this.notelist, value); }
            }
    
            public DelegateCommand DeleteCommand { get; set; }
            public DelegateCommand EditCommand { get; set; }
            public DelegateCommand AddCommand { get; set; }
    
            public  NoteListViewModel()
            {
    
               GetList();
               AddCommand = new DelegateCommand(Add);
               DeleteCommand = new DelegateCommand(Delete);
               EditCommand = new DelegateCommand(Edit);
             }
    
           private async  void GetList()
            {
    
               List list = await DataService.Current.Query();
    
               Notelist = new ObservableCollection(list);
            }
    
            private void Edit(Object paramater)
            {
                int id = (int)paramater;
                NavigationHelp.NavigateTo(typeof(MainPage), id);
            }
    
            private  void Delete(Object paramater)
            {
                int id = (int)paramater;
                DataService.Current.Delete(id);
               for (int i = 0; i < Notelist.Count; i++)
                {
                    if (Notelist[i].ID==id)
                    {
                        Notelist.RemoveAt(i);
                    }
                }
            }
    
            private void Add(Object paramater)
            {
                NavigationHelp.NavigateTo(typeof(MainPage));
            }
        }
    }

    增加修改页面的ViewModel:

    using Note.Command;
    using Note.Commons;
    using Note.Model;
    using Note.Service;
    using Note.View;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Note.ViewModel
    {
        class MainPageViewModel : ModelBase
        {
    
            private Notes notedemo;
    
            public Notes NoteDemo
            {
                get { return notedemo; }
                set
                { this.SetProperty(ref this.notedemo, value); }
            }
    
            public string  Title { get; set; }
            public DelegateCommand SaveCommand { get; set; }
            public DelegateCommand CancelCommand { get; set; }   
    
            public MainPageViewModel(int id)
            {
    
                 Query(id);
                Title = "编辑记事";
                CancelCommand = new DelegateCommand(Cancel);
                SaveCommand = new DelegateCommand(Modify);
    
            }
    
           public MainPageViewModel()
            {
                NoteDemo = new Notes();
                Title = "新建记事";
                SaveCommand = new DelegateCommand(Add);
                CancelCommand = new DelegateCommand(Cancel);
             }
    
            private async void Query(int id)
            {
                NoteDemo = await DataService.Current.Query(id);
            }
    
            private void Modify()
         {
    
             DataService.Current.Modify(NoteDemo);
             NavigationHelp.NavigateTo(typeof(NoteListView));
         }
            private void Add()
            {
                DataService.Current.Add(NoteDemo);
                NavigationHelp.NavigateTo(typeof(NoteListView));
            }
    
            private void Cancel()
            {
                NavigationHelp.NavigateTo(typeof(NoteListView));
            }
    
        }
    }

    最后还要在APP.xaml.Cs页面中建立数据库:

    StorageFolder localFolder = ApplicationData.Current.LocalFolder;
                IReadOnlyList files = await localFolder.GetFilesAsync();
                bool isExist = files.Any(file => file.Name == DbName);
                if (!isExist)
                {
                    using (var db = new SQLiteConnection(localFolder.Path + "\\note.db"))
                    {
                        db.CreateTable();
                    }
                }

     关于NavigationHelp导航类和自定义实现的命令类DelegateCommand我们之前都给出了源码.大家可以参考之前MVVM的文章.或者下载这个记事本的源码.

    记事本应用源码下载

    至此一个简单的记事本应用已经基本完成,大家可以按照我开篇提到的任意扩展.

    如果小梦的文章对你有帮助!欢迎支持小梦!



沪ICP备19023445号-2号
友情链接