在WindowsPhone中有時候我們會一些數(shù)據(jù)的存儲,這個時候我們有兩種選擇,一種是選擇存在的獨立存儲文件中,一種是存儲在數(shù)據(jù)庫中。存儲在獨立存儲文件中,這個相信很多用都會使用,這里不作為重點,本文主要講一下在WindowsPhone中使用數(shù)據(jù)庫SQL CE。
下面開始一步一步的帶領大家實現(xiàn)在WindowsPhone 中使用SQL CE數(shù)據(jù)庫。(該示例引自WindowsPhone 7應用開發(fā))
一、首先,我們需要創(chuàng)建一個EmployeeTable類,映射為數(shù)據(jù)庫中的Employee表
如下:
在創(chuàng)建之前需要添加引用:System.Data.Linq;
同時引入命名空間:using System.Data.Linq.Mapping;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | [Table]//特性標識該類為映射為數(shù)庫中的表 //該類實現(xiàn)了INotifyPropertyChanged和INotifyPropertyChanging接口 public class EmployeeTable:INotifyPropertyChanged,INotifyPropertyChanging { private int _employeeId; //將EmployeeID映射為表的主鍵,特性Column里的含義分別為:主鍵,自增,int型不為空,不為空等 [Column(IsPrimaryKey = true, IsDbGenerated = true,DbType = "INT NOT NULL Identity", CanBeNull = false, AutoSync = AutoSync.OnInsert)] public int EmployeeID { get { return _employeeId; } set { if (_employeeId != value) { NotifyPropertyChanging("EmployeeID"); _employeeId = value; NotifyPropertyChanged("EmployeeID"); } } } private string _employeeName; [Column]//EmployeeName屬性為表中EmployeeName字段 public string EmployeeName { get { return _employeeName; } set { if (_employeeName != value) { NotifyPropertyChanging("EmployeeName"); _employeeName = value; NotifyPropertyChanged("EmployeeName"); } } } private string _employeeDesc; [Column]//將EmployeeDesc屬性映射為表中EmployeeDesc字段 public string EmployeeDesc { get { return _employeeDesc; } set { if (_employeeDesc != value) { NotifyPropertyChanging("EmployeeDesc"); _employeeDesc = value; NotifyPropertyChanged("EmployeeDesc"); } } } //定義PropertyChanged事件用來通知頁面,表字段數(shù)據(jù)發(fā)生了改變 public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } //定義PropertyChanging事件通知數(shù)據(jù)上下文表的字段數(shù)據(jù)將要發(fā)生改變 public event PropertyChangingEventHandler PropertyChanging; private void NotifyPropertyChanging(string propertyname) { if (PropertyChanging != null) { PropertyChanging(this, new PropertyChangingEventArgs(propertyname)); } } } |
通過以上的這些操作,我們已經(jīng)基本上完成了Employee表的創(chuàng)建,映射為數(shù)據(jù)庫中的EmployeeTable表
二、下面我們來新建一個EmployeeDataContext.cs類文件,創(chuàng)建數(shù)據(jù)庫的DataContent,該類繼承自DataContent,在該類中定義連接字符串,如下:
首先需要引入命名空間:using system.data.Linq;
public class EmployeeDataContext:DataContext { //數(shù)據(jù)庫連接字符串 public static string DBConnectionString = "Data Source=isostore:/Employee.sdf"; //傳遞數(shù)據(jù)庫連接字符串到DataContext基類 public EmployeeDataContext(string connectionString):base(connectionString) { } //定義員工信息表 public Table<EmployeeTable> Employees; } |
三、創(chuàng)建EmployeeCollection類,該類的主要作用為頁面數(shù)據(jù)綁定的集合。如下:
//綁定頁面,進行顯示用
public class EmployeeCollection:INotifyPropertyChanged { //用于通知屬性的改變 public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this,new PropertyChangedEventArgs (propertyName)); } } private ObservableCollection<EmployeeTable> _employeeTables; |
//創(chuàng)建EmployeeTables屬性用來綁定頁面數(shù)據(jù)
public ObservableCollection<EmployeeTable> EmployeeTables { get { return _employeeTables; } set { if (_employeeTables != value) { _employeeTables = value; NotifyPropertyChanged("EmployeeTables"); } } } } |
四、這樣一個完整的數(shù)據(jù)庫就創(chuàng)建完畢了,那么我們該如何使用呢?一般的情況下我們都是在程序啟動的時候加載數(shù)據(jù)庫,為此我們可以在App.xaml文件的Launching事件中做如下處理:
using (EmployeeDataContext db=new EmployeeDataContext(EmployeeDataContext.DBConnectionString)) { if (db.DatabaseExists() == false) { db.CreateDatabase(); } } |
五、下面做一個實例進行演示:
頁面布局如下:
<phone:PhoneApplicationPage.Resources> <DataTemplate x:Key="listitem"> <Grid HorizontalAlignment="Stretch" Width="440"> <Grid.ColumnDefinitions> <ColumnDefinition Width="50"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="100"/> </Grid.ColumnDefinitions> <TextBlock Text="{Binding EmployeeName}" FontSize="{StaticResource PhoneFontSizeLarge}" Grid.Column="1" <BR>VerticalAlignment="Center"/> <Button Grid.Column="2" Click="deleteButton_Click" x:Name="deleteButton" BorderThickness="0" Margin="0" Content="刪除" ></Button> <Button Grid.Column="1" x:Name="editButton" Click="editButton_Click"BorderThickness="0" Margin="209,0,81,0" Content="編輯" <BR>Grid.ColumnSpan="2"></Button> </Grid> </DataTemplate> </phone:PhoneApplicationPage.Resources> <!--LayoutRoot 是包含所有頁面內(nèi)容的根網(wǎng)格--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel 包含應用程序的名稱和頁標題--> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="我的應用程序" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="EmployeeShow" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - 在此處放置其他內(nèi)容--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <TextBlock FontSize="24" Name="textBlock1" Text="員工名字: " Margin="12,22,330,544" /> <TextBlock FontSize="24" Margin="12,93,330,473" Name="textBlock2" Text="簡介:" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="132,6,0,0" Name="txtname" Text="" VerticalAlignment="Top" Width="281" /> <TextBox Height="72" HorizontalAlignment="Left" Margin="132,78,0,0" Name="txtdesc" Text="" VerticalAlignment="Top" Width="281" /> <Button Content="保存" Height="72" HorizontalAlignment="Left" Margin="243,150,0,0" Name="button2" VerticalAlignment="Top" Width="160" Click="button2_Click" /> <ListBox Height="293" HorizontalAlignment="Left" Margin="-12,228,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" ItemTemplate="{StaticResource listitem}" /> </Grid> </Grid> </phone:PhoneApplicationPage> |
.cs頁的處理代碼如下:
public partial class EmployeeShow : PhoneApplicationPage { //創(chuàng)建DataContext用于操作獨立的數(shù)據(jù)庫 private EmployeeDataContext employeeDB; private EmployeeCollection employeeCol = new EmployeeCollection(); |
public EmployeeShow() { InitializeComponent(); //創(chuàng)建EmployeeDataContext實例 employeeDB = new EmployeeDataContext(EmployeeDataContext.DBConnectionString); var employeeInDB = from EmployeeTable employee in employeeDB.Employees select employee; //為頁面創(chuàng)建數(shù)據(jù)綁定源 employeeCol.EmployeeTables = new System.Collections.ObjectModel.ObservableCollection<EmployeeTable>(employeeInDB); listBox1.ItemsSource = employeeCol.EmployeeTables; } |
//刪除信息
private void deleteButton_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (button != null) { EmployeeTable edelete = button.DataContext as EmployeeTable; // employeeCol.EmployeeTables.Remove(edelete); employeeDB.Employees.DeleteOnSubmit(edelete); employeeDB.SubmitChanges(); } } |
//保存信息
private void button2_Click(object sender, RoutedEventArgs e) { if (txtname.Text != "" && txtdesc.Text != "") { //編輯狀態(tài) if (State.Count > 0 && State["employee"] != null) { EmployeeTable employee = (EmployeeTable)State["employee"]; employee.EmployeeName = txtname.Text; employee.EmployeeDesc = txtdesc.Text; employeeDB.SubmitChanges(); employeeCol.EmployeeTables.Add(employee); State["employee"] = null; } Else//添加新的信息 { EmployeeTable newEmployee = new EmployeeTable { EmployeeName = txtname.Text, EmployeeDesc = txtdesc.Text }; employeeCol.EmployeeTables.Add(newEmployee); employeeDB.Employees.InsertOnSubmit(newEmployee); employeeDB.SubmitChanges(); txtname.Text = ""; txtdesc.Text = ""; } listBox1.ItemsSource = employeeCol.EmployeeTables; } else { MessageBox.Show("姓名和簡介不能為空!"); } } |
//編輯信息
private void editButton_Click(object sender, RoutedEventArgs e) { var button = sender as Button; if (button != null) { EmployeeTable eedit = button.DataContext as EmployeeTable; txtname.Text = eedit.EmployeeName; txtdesc.Text = eedit.EmployeeDesc; State["employee"] = eedit; employeeCol.EmployeeTables.Remove(eedit); } } } |
效果如圖:
好了,到這里我們已經(jīng)基本上實現(xiàn)了在WindowsPhone手機中使用SQLCE數(shù)據(jù)庫了,希望可以對朋友們有所幫助。