Windows Phone开发(48):不可或缺的本地数据库

移动开发
一个DataContext就表示一个数据库,然后在DataContext的派生类中声明N个公共字段,类型为 Table<T>,T就是你定义的实体类,一个实体类的定义就等于一个表的定义,一个DataContext的子类中定义N个 Table<T>,就如同一个数据库中包含N个表一样。我相信,只要对把LINQ和LINQ to SQL学得好,在WP中的本地数据库操作是绝对不需要学习新知识的。这也是.NET的一个不错的优点,高度集成统一。

也许WP7的时候,是想着让云服务露两手,故似乎并不支持本地数据库,所有数据都上传上“云”数据库中。不过呢,在SDK 7.1后,又加进了本地数据库功能。

这个本地数据库的操作,与我们平常在WindowsForm或WPF项目中所使用数据库的情况有些不一样:一者没有图形化的设计器;二来不使用SQL语句。

那么,你一定会问:“那用什么来处理与数据库的交互?”

不知道各位.NET基础学得怎么样,如果你的基础比较扎实,一提到不使用SQL语句也能操作数据库,你大脑里肯定闪出一道亮光,你一定想到了。

对啊,就是那个很有趣很好玩的LINQ,是啊,LINQ是什么,估计不用我介绍了,新发明,当然也不新了,呵呵。

那么,我们应该还记得Linq to SQL这个东西,各位在其他项目中一定玩得很熟,怎么玩的呢?我来帮大家回忆一下吧。在VS里面打开一个数据库,新建一个LINQ to SQL类,然后把数据库中的表拖到设计窗口,实际上,就生成了一个个实体类了。如何?有印象吧,如果没有,对不起,回去复习。

DataContext类会被翻译为“数据上下文”,读起来是不是有些莫名其妙,不管它,你就把它当成是数据库的一个代理,就好像看到它就看到数据库一样;就好比某人的照片一样,看到照片你就想起她。

也可以理解为,一个DataContext就表示一个数据库,然后在DataContext的派生类中声明N个公共字段,类型为 Table<T>,T就是你定义的实体类,一个实体类的定义就等于一个表的定义,一个DataContext的子类中定义N个 Table<T>,就如同一个数据库中包含N个表一样。

我相信,只要对把LINQ和LINQ to SQL学得好,在WP中的本地数据库操作是绝对不需要学习新知识的。这也是.NET的一个不错的优点,高度集成统一。

不过呢,连接字符串就必须了解一下了,毕竟它和其他项目中的连接字符串是不同的。

重点一:数据库的路径。数据库也是一个文件,因此,它肯定也有保存路径,我们知道WP是使用独立存储的,所以,一般情况下,我们会在独立存储中创建数据库。当然,路径有两种:

(1)以appdata开头的,如appdata:/abc.sdf,意思就是应用程序安装包里面的文件(如XAP文件),这种情况不推荐,因为我们只能通过代码来创建数据库的,而添加到VS项目中的数据库文件一般是从独立存储区中提取的,但我们不太必要这样做。

(2)以isostore开头的,如isostore:/abc.sdf,这指示数据库位于独立存储空间中。

如果各位觉得这些东西太复杂,我给大家两个连接字符串,基本上可以通过,如果没有特殊需要,侈直接照抄,然后把相关的参数改一个就是了。

***条:不带密码的:

  1. isostore:/database.sdf   

这个够简单吧,如果不带密码,就这句就够,绝对***的,其中,database.sdf是文件名,这个嘛,你自己喜欢。

第二条:带密码的,***要有密码

  1. Data Source='isostore:/database.sdf';Password='123456789' 

不多说,就是多了一个密码而已。

用这两条,基本可以走遍天下了。

没有例子是不行的,接下来,我们用实例去说明,这个实例内容不少。

在你新建WP项目后,在“解决方案资源管理器”中右击“引用”,添加引用,并找到“System.Data.Linq”。

***部分,先写好与数据库有关的逻辑。

  1. using System;   
  2. using System.Net;   
  3. using System.Windows;   
  4. using System.Windows.Controls;   
  5. using System.Windows.Documents;   
  6. using System.Windows.Ink;   
  7. using System.Windows.Input;   
  8. using System.Windows.Media;   
  9. using System.Windows.Media.Animation;   
  10. using System.Windows.Shapes;   
  11. using Microsoft.Phone.Data.Linq;   
  12. using System.Data.Linq;   
  13. using System.Data.Linq.Mapping;   
  14. using System.ComponentModel;   
  15. namespace MyApp   
  16. {   
  17.     public class MyDataContext : DataContext   
  18.     {   
  19.         /// <summary>   
  20.         /// 连接字符串   
  21.         /// </summary>   
  22.         public const string ConnectionString = "Data Source='isostore:/MyDb.sdf';Password='123456'";   
  23.         /// <summary>   
  24.         /// 构造函数   
  25.         /// </summary>   
  26.         public MyDataContext() : base(ConnectionString) { }   
  27.         public Table<Students> Students;   
  28.     }   
  29.     [Table]   
  30.     public class Students : INotifyPropertyChanged, INotifyPropertyChanging   
  31.     {   
  32.         string _stuNo;   
  33.         /// <summary>   
  34.         /// 学号   
  35.         /// </summary>   
  36.         [Column(CanBeNull = false, IsPrimaryKey = true)]   
  37.         public string StuNo   
  38.         {   
  39.             get   
  40.             {   
  41.                 return this._stuNo;   
  42.             }   
  43.             set   
  44.             {   
  45.                 if (_stuNo != value)   
  46.                 {   
  47.                     OnPropertyChanging(new PropertyChangingEventArgs("StuNo"));   
  48.                     this._stuNo = value;   
  49.                     OnPropertyChanged(new PropertyChangedEventArgs("StuNo"));   
  50.                 }   
  51.             }   
  52.         }   
  53.         string _name;   
  54.         /// <summary>   
  55.         /// 姓名   
  56.         /// </summary>   
  57.         [Column]   
  58.         public string Name   
  59.         {   
  60.             get   
  61.             {   
  62.                 return this._name;   
  63.             }   
  64.             set   
  65.             {   
  66.                 if (_name != value)   
  67.                 {   
  68.                     OnPropertyChanging(new PropertyChangingEventArgs("Name"));   
  69.                     _name = value;   
  70.                     OnPropertyChanged(new PropertyChangedEventArgs("Name"));   
  71.                 }   
  72.             }   
  73.         }   
  74.         string _email;   
  75.         /// <summary>   
  76.         /// 电邮   
  77.         /// </summary>   
  78.         [Column]   
  79.         public string Email   
  80.         {   
  81.             get   
  82.             {   
  83.                 return this._email;   
  84.             }   
  85.             set   
  86.             {   
  87.                 if (_email != value)   
  88.                 {   
  89.                     OnPropertyChanging(new PropertyChangingEventArgs("Email"));   
  90.                     _email = value;   
  91.                     OnPropertyChanged(new PropertyChangedEventArgs("Email"));   
  92.                 }   
  93.             }   
  94.         }   
  95.         public event PropertyChangingEventHandler PropertyChanging;   
  96.         public event PropertyChangedEventHandler PropertyChanged;   
  97.         protected void OnPropertyChanging(PropertyChangingEventArgs e)   
  98.         {   
  99.             if (PropertyChanging != null)   
  100.             {   
  101.                 PropertyChanging(this, e);   
  102.             }   
  103.         }   
  104.         protected void OnPropertyChanged(PropertyChangedEventArgs e)   
  105.         {   
  106.             if (PropertyChanged != null)   
  107.             {   
  108.                 PropertyChanged(this, e);   
  109.             }   
  110.         }   
  111.     }   
  112. }   

注意,实体类必须要实现INotifyPropertyChanged接口,***连同INotifyPropertyChanging接口,这样可 以改善性能。记住了,一定要实现这两个接口,而且要触发PropertyChanging和PropertyChanged事件,不然你提交到数据库是不 能更新数据的。

这个我想不难懂,因为在WPF里面也是这样的,除非你把实体类的属性都定义为依赖项属性,但***不要这样,依赖项属性虽然节约内存,但是因为它需要进行全局注册,有可能会拖延应用程序的启动时间。

第二部分,创建数据库。

独立存储本来是没有数据库的,所以,在***次使用应用程序时,必须先创建数据库,你说,在什么时候创建呢?想来想去,还是在应用程序类的构造函数中判断数据库是否存在,如果不存在,就创建。

  1. using (MyDataContext dc = new MyDataContext())   
  2. {   
  3.     if (dc.DatabaseExists() == false)   
  4.     {   
  5.         dc.CreateDatabase();   
  6.     }   
  7. }   

以上代码是写在App类的构造函数中。

第三部分,应用程序页面。

我们做一个简单的“学员信息登记系统”,道先应用程序运行时打开主页,主页上显示已经添加到数据库中的学员信息,在列表上每条记录都有两个操作按钮:“编辑”按钮点击后会跳到修改页,允许用户修改学员信息;“删除”按钮不用我说了,一去不复返。

主页一下方的应用程序栏中有两个按钮,“刷新”和“新增”,刷新不用解释,新增就是跳到新增页面,输入新学员信息,然后保存。

先看看几个效果图吧。

首先,我们要用到一个图标,不用自己做,SDK自带了一堆,在这里可以找到C:\Program Files (x86)\Microsoft SDKs\Windows Phone\v7.1\Icons\dark,看到喜欢的添加到项目中即可,生成操作设为“内容”,“如果较新则复制”。

别走开,下页更精彩~

#p#

主页:MainPage.xaml

  1. <phone:PhoneApplicationPage    
  2.     x:Class="MyApp.MainPage"   
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"   
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"   
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  9.     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="696"   
  10.     FontFamily="{StaticResource PhoneFontFamilyNormal}"   
  11.     FontSize="{StaticResource PhoneFontSizeNormal}"   
  12.     Foreground="{StaticResource PhoneForegroundBrush}"   
  13.     SupportedOrientations="Portrait" Orientation="Portrait"   
  14.     shell:SystemTray.IsVisible="True">   
  15.     <!--LayoutRoot 是包含所有页面内容的根网格-->   
  16.     <Grid x:Name="LayoutRoot" Background="Transparent">   
  17.         <Grid.RowDefinitions>   
  18.             <RowDefinition Height="Auto"/>   
  19.             <RowDefinition Height="*"/>   
  20.         </Grid.RowDefinitions>   
  21.         <!--TitlePanel 包含应用程序的名称和页标题-->   
  22.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">   
  23.             <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>   
  24.             <TextBlock x:Name="PageTitle" Text="学员列表" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>   
  25.         </StackPanel>   
  26.         <!--ContentPanel - 在此处放置其他内容-->   
  27.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">   
  28.             <ListBox Name="stuList" HorizontalContentAlignment="Center">   
  29.                 <ListBox.ItemTemplate>   
  30.                     <DataTemplate>   
  31.                         <Grid Margin="2,10,2,2">   
  32.                             <Grid.RowDefinitions>   
  33.                                 <RowDefinition Height="auto"/>   
  34.                                 <RowDefinition Height="auto"/>   
  35.                                 <RowDefinition Height="auto"/>   
  36.                             </Grid.RowDefinitions>   
  37.                             <Grid.ColumnDefinitions>   
  38.                                 <ColumnDefinition Width="Auto" />   
  39.                                 <ColumnDefinition />   
  40.                                 <ColumnDefinition Width="Auto" />   
  41.                             </Grid.ColumnDefinitions>   
  42.                             <TextBlock Grid.Column="0"   
  43.                                        Grid.Row="0"   
  44.                                        Text="学号:"/>   
  45.                             <TextBlock Grid.Column="0"   
  46.                                        Grid.Row="1"   
  47.                                        Text="姓名:"/>   
  48.                             <TextBlock Grid.Column="0"   
  49.                                        Grid.Row="2"   
  50.                                        Text="电邮:"/>   
  51.                             <TextBlock Grid.Column="1"   
  52.                                        Grid.Row="0"   
  53.                                        Text="{Binding StuNo}"/>   
  54.                             <TextBlock Grid.Column="1"   
  55.                                        Grid.Row="1"   
  56.                                        Text="{Binding Name}"/>   
  57.                             <TextBlock Grid.Column="1"   
  58.                                        Grid.Row="2"   
  59.                                        Text="{Binding Email}"/>   
  60.                             <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="1" Grid.RowSpan="2">   
  61.                                 <Button BorderThickness="0"   
  62.                                         Tag="{Binding StuNo}"   
  63.                                         Click="OnDataEdit"   
  64.                                         Margin="-5">   
  65.                                     <Button.Content>   
  66.                                         <Image Stretch="Uniform" Source="appbar.edit.rest.png"/>   
  67.                                     </Button.Content>   
  68.                                 </Button>   
  69.                                 <Button Tag="{Binding StuNo}"   
  70.                                         Click="OnDataDelete"   
  71.                                         BorderThickness="0" Margin="-5">   
  72.                                     <Button.Content>   
  73.                                         <Image Stretch="Uniform" Source="appbar.delete.rest.png"/>   
  74.                                     </Button.Content>   
  75.                                 </Button>   
  76.                             </StackPanel>   
  77.                         </Grid>   
  78.                     </DataTemplate>   
  79.                 </ListBox.ItemTemplate>   
  80.                 <ListBox.ItemContainerStyle>   
  81.                     <Style TargetType="ListBoxItem">   
  82.                         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>   
  83.                     </Style>   
  84.                 </ListBox.ItemContainerStyle>   
  85.             </ListBox>   
  86.         </Grid>   
  87.     </Grid>   
  88.     <phone:PhoneApplicationPage.ApplicationBar>   
  89.         <shell:ApplicationBar>   
  90.             <shell:ApplicationBarIconButton Text="刷新" IconUri="appbar.refresh.rest.png" Click="onRefresh"/>   
  91.             <shell:ApplicationBarIconButton Text="新增" IconUri="appbar.add.rest.png" Click="onNew"/>   
  92.         </shell:ApplicationBar>   
  93.     </phone:PhoneApplicationPage.ApplicationBar>   
  94. </phone:PhoneApplicationPage>   

ListBox由于显示的项结构复杂,所以就搞了个自定义数据模板。

MainPage.xaml.cs中的代码如下:

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Windows;   
  6. using System.Windows.Controls;   
  7. using System.Windows.Documents;   
  8. using System.Windows.Input;   
  9. using System.Windows.Media;   
  10. using System.Windows.Media.Animation;   
  11. using System.Windows.Shapes;   
  12. using Microsoft.Phone.Controls;   
  13. namespace MyApp   
  14. {   
  15.     public partial class MainPage : PhoneApplicationPage   
  16.     {   
  17.         // 构造函数   
  18.         public MainPage()   
  19.         {   
  20.             InitializeComponent();   
  21.         }   
  22.         // 编辑   
  23.         private void OnDataEdit(object sender, RoutedEventArgs e)   
  24.         {   
  25.             Button btn = e.OriginalSource as Button;   
  26.             if (btn != null)   
  27.             {   
  28.                 string no = btn.Tag as string;   
  29.                 NavigationService.Navigate(new Uri("/EditPage.xaml?sno=" + no, UriKind.Relative));   
  30.             }   
  31.         }   
  32.         // 删除数据   
  33.         private void OnDataDelete(object sender, RoutedEventArgs e)   
  34.         {   
  35.             Button btn = e.OriginalSource as Button;   
  36.             if (btn != null)   
  37.             {   
  38.                 string sNo = btn.Tag.ToString();   
  39.                 using (MyDataContext dc = new MyDataContext())   
  40.                 {   
  41.                     Students stu = dc.Students.FirstOrDefault(s => s.StuNo == sNo);   
  42.                     if (stu != null)   
  43.                     {   
  44.                         dc.Students.DeleteOnSubmit(stu);   
  45.                         dc.SubmitChanges();   
  46.                         BindList();   
  47.                     }   
  48.                 }   
  49.             }   
  50.         }   
  51.         private void onRefresh(object sender, EventArgs e)   
  52.         {   
  53.             BindList();   
  54.         }   
  55.         // 新增   
  56.         private void onNew(object sender, EventArgs e)   
  57.         {   
  58.             NavigationService.Navigate(new Uri("/AddPage.xaml", UriKind.Relative));   
  59.         }   
  60.         /// <summary>   
  61.         /// 把数据绑定到ListBox   
  62.         /// </summary>   
  63.         private void BindList()   
  64.         {   
  65.             using (MyDataContext dc = new MyDataContext())   
  66.             {   
  67.                 var res =   
  68.                     from s in dc.Students   
  69.                     select s;   
  70.                 this.stuList.ItemsSource = res.ToList();   
  71.             }   
  72.         }   
  73.         protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)   
  74.         {   
  75.             base.OnNavigatedTo(e);   
  76.             BindList();   
  77.         }   
  78.     }   
  79. }   

新增页:AddPage.xaml

  1. <phone:PhoneApplicationPage    
  2.     x:Class="MyApp.AddPage"   
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"   
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"   
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  9.     FontFamily="{StaticResource PhoneFontFamilyNormal}"   
  10.     FontSize="{StaticResource PhoneFontSizeNormal}"   
  11.     Foreground="{StaticResource PhoneForegroundBrush}"   
  12.     SupportedOrientations="Portrait" Orientation="Portrait"   
  13.     mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"   
  14.     shell:SystemTray.IsVisible="True">   
  15.     <!--LayoutRoot 是包含所有页面内容的根网格-->   
  16.     <Grid x:Name="LayoutRoot" Background="Transparent">   
  17.         <Grid.RowDefinitions>   
  18.             <RowDefinition Height="Auto"/>   
  19.             <RowDefinition Height="*"/>   
  20.         </Grid.RowDefinitions>   
  21.         <!--TitlePanel 包含应用程序的名称和页标题-->   
  22.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">   
  23.             <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>   
  24.             <TextBlock x:Name="PageTitle" Text="新增记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>   
  25.         </StackPanel>   
  26.         <!--ContentPanel - 在此处放置其他内容-->   
  27.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">   
  28.             <StackPanel>   
  29.                 <TextBlock Text="学号:"/>   
  30.                 <TextBox Name="txtNo"/>   
  31.                 <TextBlock Text="姓名:" Margin="0,7,0,0"/>   
  32.                 <TextBox Name="txtName"/>   
  33.                 <TextBlock Margin="0,7,0,0" Text="Email:"/>   
  34.                 <TextBox Name="txtEmail"/>   
  35.             </StackPanel>   
  36.         </Grid>   
  37.     </Grid>   
  38.     <phone:PhoneApplicationPage.ApplicationBar>   
  39.         <shell:ApplicationBar IsVisible="True">   
  40.             <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>   
  41.             <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>   
  42.         </shell:ApplicationBar>   
  43.     </phone:PhoneApplicationPage.ApplicationBar>   
  44. </phone:PhoneApplicationPage>   

AddPage.xaml.cs中的代码如下:

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Windows;   
  6. using System.Windows.Controls;   
  7. using System.Windows.Documents;   
  8. using System.Windows.Input;   
  9. using System.Windows.Media;   
  10. using System.Windows.Media.Animation;   
  11. using System.Windows.Shapes;   
  12. using Microsoft.Phone.Controls;   
  13.    
  14. namespace MyApp   
  15. {   
  16.     public partial class AddPage : PhoneApplicationPage   
  17.     {   
  18.         public AddPage()   
  19.         {   
  20.             InitializeComponent();   
  21.         }   
  22.    
  23.         private void onCancel(object sender, EventArgs e)   
  24.         {   
  25.             //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
  26.             if (NavigationService.CanGoBack)   
  27.             {   
  28.                 NavigationService.GoBack();   
  29.             }   
  30.         }   
  31.    
  32.         private void onSave(object sender, EventArgs e)   
  33.         {   
  34.             if (txtNo.Text == "")   
  35.             {   
  36.                 MessageBox.Show("学号不能为空。"); return;   
  37.             }   
  38.             if (txtName.Text == "")   
  39.             {   
  40.                 MessageBox.Show("姓名不能为空。"); return;   
  41.             }   
  42.    
  43.             using (MyDataContext dc = new MyDataContext())   
  44.             {   
  45.                 if (dc.Students.Where(c=>c.StuNo == txtNo.Text).Count() > 0)   
  46.                 {   
  47.                     MessageBox.Show("输入的学号已经存在。"); return;   
  48.                 }   
  49.    
  50.                 Students stu = new Students()   
  51.                 {   
  52.                     StuNo = txtNo.Text,   
  53.                     Name = txtName.Text,   
  54.                     Email = txtEmail.Text   
  55.                 };   
  56.                 dc.Students.InsertOnSubmit(stu);   
  57.                 dc.SubmitChanges();   
  58.             }   
  59.             //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
  60.             if (NavigationService.CanGoBack)   
  61.             {   
  62.                 NavigationService.GoBack();   
  63.             }   
  64.         }   
  65.     }   
  66. }   

编辑页:EditPage.xaml

  1. <phone:PhoneApplicationPage    
  2.     x:Class="MyApp.EditPage"   
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"   
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"   
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   
  9.     FontFamily="{StaticResource PhoneFontFamilyNormal}"   
  10.     FontSize="{StaticResource PhoneFontSizeNormal}"   
  11.     Foreground="{StaticResource PhoneForegroundBrush}"   
  12.     SupportedOrientations="Portrait" Orientation="Portrait"   
  13.     mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"   
  14.     shell:SystemTray.IsVisible="True">   
  15.    
  16.     <!--LayoutRoot 是包含所有页面内容的根网格-->   
  17.     <Grid x:Name="LayoutRoot" Background="Transparent">   
  18.         <Grid.RowDefinitions>   
  19.             <RowDefinition Height="Auto"/>   
  20.             <RowDefinition Height="*"/>   
  21.         </Grid.RowDefinitions>   
  22.    
  23.         <!--TitlePanel 包含应用程序的名称和页标题-->   
  24.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">   
  25.             <TextBlock x:Name="ApplicationTitle" Text="我的应用程序" Style="{StaticResource PhoneTextNormalStyle}"/>   
  26.             <TextBlock x:Name="PageTitle" Text="编辑记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>   
  27.         </StackPanel>   
  28.    
  29.         <!--ContentPanel - 在此处放置其他内容-->   
  30.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">   
  31.             <StackPanel>   
  32.                 <TextBlock Text="学号:"/>   
  33.                 <TextBlock Name="txtNo"/>   
  34.                 <TextBlock Text="姓名:" Margin="0,7,0,0"/>   
  35.                 <TextBox Name="txtName"/>   
  36.                 <TextBlock Margin="0,7,0,0" Text="Email:"/>   
  37.                 <TextBox Name="txtEmail"/>   
  38.             </StackPanel>   
  39.         </Grid>   
  40.     </Grid>   
  41.     
  42.     <phone:PhoneApplicationPage.ApplicationBar>   
  43.         <shell:ApplicationBar IsVisible="True">   
  44.             <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>   
  45.             <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>   
  46.         </shell:ApplicationBar>   
  47.     </phone:PhoneApplicationPage.ApplicationBar>   
  48.    
  49. </phone:PhoneApplicationPage>  

EditPage.xaml.cs中的代码如下:

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Net;   
  5. using System.Windows;   
  6. using System.Windows.Controls;   
  7. using System.Windows.Documents;   
  8. using System.Windows.Input;   
  9. using System.Windows.Media;   
  10. using System.Windows.Media.Animation;   
  11. using System.Windows.Shapes;   
  12. using Microsoft.Phone.Controls;   
  13.    
  14. namespace MyApp   
  15. {   
  16.     public partial class EditPage : PhoneApplicationPage   
  17.     {   
  18.         public EditPage()   
  19.         {   
  20.             InitializeComponent();   
  21.         }   
  22.    
  23.         private void onSave(object sender, EventArgs e)   
  24.         {   
  25.             if (txtName.Text == "" )   
  26.             {   
  27.                 MessageBox.Show("姓名不能为空。"); return;   
  28.             }   
  29.    
  30.             using (MyDataContext dc = new MyDataContext())   
  31.             {   
  32.                 Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);   
  33.                 if (stu != null)   
  34.                 {   
  35.                     stu.Name = txtName.Text;   
  36.                     stu.Email = txtEmail.Text;   
  37.                     dc.SubmitChanges();   
  38.                 }   
  39.             }   
  40.             //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
  41.             if (NavigationService.CanGoBack)   
  42.             {   
  43.                 NavigationService.GoBack();   
  44.             }   
  45.         }   
  46.    
  47.         private void onCancel(object sender, EventArgs e)   
  48.         {   
  49.             //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
  50.             if (NavigationService.CanGoBack)   
  51.             {   
  52.                 NavigationService.GoBack();   
  53.             }   
  54.         }   
  55.    
  56.         protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)   
  57.         {   
  58.             base.OnNavigatedTo(e);   
  59.    
  60.             if (NavigationContext.QueryString.ContainsKey("sno"))   
  61.             {   
  62.                 txtNo.Text = NavigationContext.QueryString["sno"];   
  63.                 using (MyDataContext dc = new MyDataContext())   
  64.                 {   
  65.                     Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);   
  66.                     if (stu != null)   
  67.                     {   
  68.                         txtName.Text = stu.Name;   
  69.                         txtEmail.Text = stu.Email;   
  70.                     }   
  71.                 }   
  72.             }   
  73.         }   
  74.     }   
  75. }   

代码贴完了,因为实在不太好解释,而且也不算很复杂,相信各位能看得懂。

但这次的例子,代码实在有点多,所以,我会上传到“资源”中,大家去下载之后再看吧,在VS里面看代码舒服一些。

责任编辑:闫佳明 来源: oschina
相关推荐

2019-08-05 10:00:13

LinuxBash命令

2021-11-30 05:51:46

React开发工具

2010-04-21 13:52:17

Oracle数据库性能

2012-04-18 17:06:41

PhoneGap

2013-01-04 09:53:32

大数据技术大数据

2011-06-14 08:54:46

MangoWindows Pho

2020-05-07 18:20:52

Git脚本Linux开源

2013-09-18 09:40:32

企业BYOD企业应用商店

2024-01-12 07:32:35

数据科学Python库项目

2020-11-09 06:51:46

开源工具开源

2020-10-27 12:43:53

数据分析技术工具

2017-03-27 17:53:45

Linux

2014-01-09 14:25:19

MacOS X工具

2013-09-24 10:32:31

Android开发者工具

2015-05-07 13:38:15

2011-02-22 08:55:42

Chrome企业浏览器

2011-06-13 13:42:29

2022-11-08 08:49:09

IT专家职业要素

2022-03-29 10:03:12

IT领导者首席信息官
点赞
收藏

51CTO技术栈公众号