Windows Phone 本地数据库的操作

App.xaml

#region 创建数据库
using (MyDataContext dc = new MyDataContext())
{ if (dc.DatabaseExists() == false) { dc.CreateDatabase(); } } #endregion

 

MainPage.xaml

<phone:PhoneApplicationPage 
    x:Class="LocalDataBase.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="696"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot 是包含所有页面内容的根网格-->
    <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="学员列表" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - 在此处放置其他内容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox Name="stuList" HorizontalContentAlignment="Center">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid Margin="2,10,2,2">
                            <Grid.RowDefinitions>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                                <RowDefinition Height="auto"/>
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition Width="Auto" />
                                <ColumnDefinition />
                                <ColumnDefinition Width="Auto" />
                            </Grid.ColumnDefinitions>
                            <TextBlock Grid.Column="0"
                                       Grid.Row="0"
                                       Text="学号:"/>
                            <TextBlock Grid.Column="0"
                                       Grid.Row="1"
                                       Text="姓名:"/>
                            <TextBlock Grid.Column="0"
                                       Grid.Row="2"
                                       Text="电邮:"/>
                            <TextBlock Grid.Column="1"
                                       Grid.Row="0"
                                       Text="{Binding StuNo}"/>
                            <TextBlock Grid.Column="1"
                                       Grid.Row="1"
                                       Text="{Binding Name}"/>
                            <TextBlock Grid.Column="1"
                                       Grid.Row="2"
                                       Text="{Binding Email}"/>
                            <StackPanel Orientation="Horizontal" Grid.Column="2" Grid.Row="1" Grid.RowSpan="2">
                                <Button BorderThickness="0"
                                        Tag="{Binding StuNo}"
                                        Click="OnDataEdit"
                                        Margin="-5">
                                    <Button.Content>
                                        <Image Stretch="Uniform" Source="/Images/edit.png"/>
                                    </Button.Content>
                                </Button>
                                <Button Tag="{Binding StuNo}"
                                        Click="OnDataDelete"
                                        BorderThickness="0" Margin="-5">
                                    <Button.Content>
                                        <Image Stretch="Uniform" Source="/Images/deleted.png"/>
                                    </Button.Content>
                                </Button>
                            </StackPanel>
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
                    </Style>
                </ListBox.ItemContainerStyle>
            </ListBox>
        </Grid>
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar>
            <shell:ApplicationBarIconButton Text="刷新" IconUri="appbar.refresh.rest.png" Click="onRefresh"/>
            <shell:ApplicationBarIconButton Text="新增" IconUri="appbar.add.rest.png" Click="onNew"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace LocalDataBase
{
    public partial class MainPage : PhoneApplicationPage
    {
        // 构造函数   
        public MainPage()
        {
            InitializeComponent();
        }

        // 编辑   
        private void OnDataEdit(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                string no = btn.Tag as string;
                NavigationService.Navigate(new Uri("/EditPage.xaml?sno=" + no, UriKind.Relative));
            }
        }

        // 删除数据   
        private void OnDataDelete(object sender, RoutedEventArgs e)
        {
            Button btn = e.OriginalSource as Button;
            if (btn != null)
            {
                string sNo = btn.Tag.ToString();
                using (MyDataContext dc = new MyDataContext())
                {
                    Students stu = dc.Students.FirstOrDefault(s => s.StuNo == sNo);
                    if (stu != null)
                    {
                        dc.Students.DeleteOnSubmit(stu);
                        dc.SubmitChanges();
                        BindList();
                    }
                }
            }
        }

        private void onRefresh(object sender, EventArgs e)
        {
            BindList();
        }

        // 新增   
        private void onNew(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddPage.xaml", UriKind.Relative));
        }

        /// <summary>   
        /// 把数据绑定到ListBox   
        /// </summary>   
        private void BindList()
        {
            using (MyDataContext dc = new MyDataContext())
            {
                var res =
                    from s in dc.Students
                    select s;
                this.stuList.ItemsSource = res.ToList();
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            BindList();
        }
    }
}

AddPage.xaml

<phone:PhoneApplicationPage 
    x:Class="LocalDataBase.AddPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot 是包含所有页面内容的根网格-->
    <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="新增记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - 在此处放置其他内容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel>
                <TextBlock Text="学号:"/>
                <TextBox Name="txtNo"/>
                <TextBlock Text="姓名:" Margin="0,7,0,0"/>
                <TextBox Name="txtName"/>
                <TextBlock Margin="0,7,0,0" Text="Email:"/>
                <TextBox Name="txtEmail"/>
            </StackPanel>
        </Grid>
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True">
            <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>
            <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace LocalDataBase
{
    public partial class AddPage : PhoneApplicationPage
    {
        public AddPage()
        {
            InitializeComponent();
        }

        private void onCancel(object sender, EventArgs e)
        {
            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        private void onSave(object sender, EventArgs e)
        {
            if (txtNo.Text == "")
            {
                MessageBox.Show("学号不能为空。"); return;
            }
            if (txtName.Text == "")
            {
                MessageBox.Show("姓名不能为空。"); return;
            }

            using (MyDataContext dc = new MyDataContext())
            {
                if (dc.Students.Where(c => c.StuNo == txtNo.Text).Count() > 0)
                {
                    MessageBox.Show("输入的学号已经存在。"); return;
                }

                Students stu = new Students()
                {
                    StuNo = txtNo.Text,
                    Name = txtName.Text,
                    Email = txtEmail.Text
                };
                dc.Students.InsertOnSubmit(stu);
                dc.SubmitChanges();
            }
            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }
    }
}

EditPage.xaml

<phone:PhoneApplicationPage 
    x:Class="LocalDataBase.EditPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot 是包含所有页面内容的根网格-->
    <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="编辑记录" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>

        <!--ContentPanel - 在此处放置其他内容-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <StackPanel>
                <TextBlock Text="学号:"/>
                <TextBlock Name="txtNo"/>
                <TextBlock Text="姓名:" Margin="0,7,0,0"/>
                <TextBox Name="txtName"/>
                <TextBlock Margin="0,7,0,0" Text="Email:"/>
                <TextBox Name="txtEmail"/>
            </StackPanel>
        </Grid>
    </Grid>

    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True">
            <shell:ApplicationBarIconButton IconUri="appbar.save.rest.png" Text="保存" Click="onSave"/>
            <shell:ApplicationBarIconButton IconUri="appbar.cancel.rest.png" Text="取消" Click="onCancel"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace LocalDataBase
{
    public partial class EditPage : PhoneApplicationPage
    {
        public EditPage()
        {
            InitializeComponent();
        }

        private void onSave(object sender, EventArgs e)
        {
            if (txtName.Text == "")
            {
                MessageBox.Show("姓名不能为空。"); return;
            }

            using (MyDataContext dc = new MyDataContext())
            {
                Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);
                if (stu != null)
                {
                    stu.Name = txtName.Text;
                    stu.Email = txtEmail.Text;
                    dc.SubmitChanges();
                }
            }
            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        private void onCancel(object sender, EventArgs e)
        {
            //NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));   
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            if (NavigationContext.QueryString.ContainsKey("sno"))
            {
                txtNo.Text = NavigationContext.QueryString["sno"];
                using (MyDataContext dc = new MyDataContext())
                {
                    Students stu = dc.Students.FirstOrDefault(s => s.StuNo == txtNo.Text);
                    if (stu != null)
                    {
                        txtName.Text = stu.Name;
                        txtEmail.Text = stu.Email;
                    }
                }
            }
        }
    }
}

MyDataContext.cs

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

using Microsoft.Phone.Data.Linq;
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.ComponentModel;

namespace LocalDataBase
{
    public class MyDataContext : DataContext
    {
        /// <summary>   
        /// 连接字符串   
        /// </summary>   
        public const string ConnectionString = "Data Source='isostore:/MyDb.sdf';Password='123456'";
        /// <summary>   
        /// 构造函数   
        /// </summary>   
        public MyDataContext() : base(ConnectionString) { }

        public Table<Students> Students;
    }


    [Table]
    public class Students : INotifyPropertyChanged, INotifyPropertyChanging
    {
        string _stuNo;
        /// <summary>   
        /// 学号   
        /// </summary>   
        [Column(CanBeNull = false, IsPrimaryKey = true)]
        public string StuNo
        {
            get
            {
                return this._stuNo;
            }
            set
            {
                if (_stuNo != value)
                {
                    OnPropertyChanging(new PropertyChangingEventArgs("StuNo"));
                    this._stuNo = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("StuNo"));
                }
            }
        }

        string _name;
        /// <summary>   
        /// 姓名   
        /// </summary>   
        [Column]
        public string Name
        {
            get
            {
                return this._name;
            }
            set
            {
                if (_name != value)
                {
                    OnPropertyChanging(new PropertyChangingEventArgs("Name"));
                    _name = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Name"));
                }
            }
        }

        string _email;
        /// <summary>   
        /// 电邮   
        /// </summary>   
        [Column]
        public string Email
        {
            get
            {
                return this._email;
            }
            set
            {
                if (_email != value)
                {
                    OnPropertyChanging(new PropertyChangingEventArgs("Email"));
                    _email = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("Email"));
                }
            }
        }

        public event PropertyChangingEventHandler PropertyChanging;

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanging(PropertyChangingEventArgs e)
        {
            if (PropertyChanging != null)
            {
                PropertyChanging(this, e);
            }
        }

        protected void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, e);
            }
        }
    }
}

 

posted on 2013-06-04 17:51  Hai_阔天空  阅读(202)  评论(0)    收藏  举报

导航