Windows Phone 7记事本的第二部分讲解记事本的基本功能。

  

  功能点: 

  1.添加日记功能

  2.修改日记功能

  3.删除日记功能

  4.简单帮助功能

  5.显示已写日记列表功能

  一、显示已写日记列表功能

  1.新建Note类,包含日记文件的相关信息,供我们做数据绑定使用。如下

     public class Note
      {

      //文件创建日期
          public string DateCreated { get; set; }

      //文件全名(包含日期)
          public string FileFullName { get; set; }

      //我们命名的文件名
          public string FileName { get; set; }
      }

  2.修改MainPage页面

  首先我们在MainPage页面中添加如下XAML标记,以显示已写日记列表。

       <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                     x:Name="noteListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <HyperlinkButton x:Name="noteLocation"
                                             FontSize="32"
                                             Content="{Binding FileName}"
                                             Tag="{Binding FileFullName}"
                                             Click="noteLocation_Click">
                            </HyperlinkButton>
                            <TextBlock Name="noteDateCreated"
                                       Text="{Binding DateCreated}"
                                       Margin="10">
                            </TextBlock>
                        </StackPanel>

</DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

  说明:我们定义一个ListBox对象,用来显示已写日记列表,在它的模板中,我们包含了一个HyperlinkButton和一个TextBlock对象,其中HyperlinkButton对象用来显示我们日记的名称,它的Tag绑定了Note对象的FileFullName属性,Content属性绑定了Note对象的FileName属性,通过点击它可以导航到编辑日记界面,这样我们就可以编辑我们的日记了。TextBlock对象用来显示我们创建日记的日期,Text属性绑定了Note对象的DateCreated属性。下面我们看一下HyperlinkButton的noteLocation_Click事件。

 

     private void noteLocation_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton clickedLink = (HyperlinkButton)sender;

      //将clickedLink的Tag值传到ViewEdit.xaml页面中。            
            string uri = string.Format("/XapNote;component/ViewEdit.xaml?id={0}", clickedLink.Tag);

NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

 

private void bindList()
        {
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            List<Note> notes = new List<Note>();
           
            string[] fileList = appStorage.GetFileNames();

foreach (var file in fileList)
            {
                if (file != "__ApplicationSettings")
                {
                    //2010_12_30_14_02_01_ddd.txt  文件全名的格式,2010_12_30_14_02_01是创建日记的日期,ddd是我们命名的日记名。下面就是从文件全名中截取信息
                    string fileFullName = file;

string year = file.Substring(0, 4);
                    string month = file.Substring(5, 2);
                    string day = file.Substring(8, 2);
                    string hour = file.Substring(11, 2);
                    string minute = file.Substring(14, 2);
                    string second = file.Substring(17, 2);
                    DateTime dateTime = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), int.Parse(hour), int.Parse(minute), int.Parse(second));
                    string dateCreated = dateTime.ToString("yyyy年MM月dd日 HH:MM:ss");
                    string fileName = file.Substring(20);

fileName = fileName.Substring(0, fileName.Length - 4);

notes.Add(new Note() { FileFullName = fileFullName, DateCreated = dateCreated, FileName = fileName });
                }
            }

noteListBox.ItemsSource = notes;
        }

  说明:由于我们写的日记保存在独立存储空间内,所以我们首先获取程序的IsolatedStorageFile对象,通过 appStorage.GetFileNames()方法我们可以获得程序的独立存储空间中的所有文件,这些文件中包含一个系统自带的设置文件"__ApplicationSettings"所以将其排除,然后从文件中截取字符串来获取日期,和我们定义的文件名,以供我们使用,然后将截取到的信息保存在Note对象中,来绑定数据到ListBox对象。在PhoneApplicationPage_Loaded方法中调用此方法。

  二、简单帮助功能

  1.修改MainPage页面

  在xaml文件添加如下标记

   <Canvas Name="helpCanvas"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Width="400"
                    Height="400"
                    Background="White"
                    Visibility="Collapsed">

<ScrollViewer Name="helpScrollViewer"
                              Width="400"
                              Height="300"
                              Canvas.Left="0"
                              Canvas.Top="100">
                    <TextBlock Name="helpTextBlock" Foreground="Black" FontSize="24" Height="500" TextWrapping="Wrap">
                        这个记事本允许你写简单的日记,并且将其保存,显示你创建日记的日期和地点。
                        <LineBreak></LineBreak>
                        <LineBreak></LineBreak>
                        点击日记名称,可以打开并编辑该日记。
                        <LineBreak></LineBreak>
                        <LineBreak></LineBreak>
                        点击应用程序下面的添加图标可以写日记。
                        <LineBreak></LineBreak></TextBlock>
                </ScrollViewer>
                <TextBlock TextAlignment="Center" Foreground="Black" Canvas.Left="0" Canvas.Top="10" Height="30" Text="帮助" Width="59" />
                <Button x:Name="btnClose"
                        Click="btnClose_Click"
                        Width="50"
                        Height="50"
                        Canvas.Left="350"
                        Canvas.Top="0">
                    <Button.Background>
                        <ImageBrush ImageSource="/Images/appbar.close.rest.png" Stretch="None" />
                    </Button.Background>
                </Button>
            </Canvas>

    ......

     <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="添加"  Click="Appbar_Add_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.questionmark.rest.png" Text="帮助" Click="Appbar_Help_Click"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

  说明:我们首先定义一个Canvas对象,初始化设置为隐藏Visibility="Collapsed",当点击MainPage页面中的帮助图标时它将显示,它里面包含了ScrollViewer对象,此对象中的TextBlock用来显示帮助信息。还有一个Button,当点击它的时候此Canvas对象隐藏。由于此功能只是Canvas对象显示与隐藏的特点,所以不再赘述,有兴趣的朋友可以下载我的代码,自己看看。

  完整MainPage.xaml文件代码如下:

<phone:PhoneApplicationPage
    x:Class="XapNote.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="PortraitOrLandscape" Orientation="Portrait"
    shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="记事本" Style="{StaticResource PhoneTextNormalStyle}" FontSize="30" />
            <TextBlock x:Name="PageTitle" Text="我的日记" Margin="9,-7,0,0" TextAlignment="Center" FontSize="22"/>
        </StackPanel>

<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
                     x:Name="noteListBox">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <HyperlinkButton x:Name="noteLocation"
                                             FontSize="32"
                                             Content="{Binding FileName}"
                                             Tag="{Binding FileFullName}"
                                             Click="noteLocation_Click">
                            </HyperlinkButton>
                            <TextBlock Name="noteDateCreated"
                                       Text="{Binding DateCreated}"
                                       Margin="10">
                            </TextBlock>
                        </StackPanel>

</DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

<Canvas Name="helpCanvas"
                    HorizontalAlignment="Stretch"
                    VerticalAlignment="Stretch"
                    Width="400"
                    Height="400"
                    Background="White"
                    Visibility="Collapsed">

<ScrollViewer Name="helpScrollViewer"
                              Width="400"
                              Height="300"
                              Canvas.Left="0"
                              Canvas.Top="100">
                    <TextBlock Name="helpTextBlock" Foreground="Black" FontSize="24" Height="500" TextWrapping="Wrap">
                        这个记事本允许你写简单的日记,并且将其保存,显示你创建日记的日期和地点。
                        <LineBreak></LineBreak>
                        <LineBreak></LineBreak>
                        点击日记名称,可以打开并编辑该日记。
                        <LineBreak></LineBreak>
                        <LineBreak></LineBreak>
                        点击应用程序下面的添加图标可以写日记。
                        <LineBreak></LineBreak></TextBlock>
                </ScrollViewer>
                <TextBlock TextAlignment="Center" Foreground="Black" Canvas.Left="0" Canvas.Top="10" Height="30" Text="帮助" Width="59" />
                <Button x:Name="btnClose"
                        Click="btnClose_Click"
                        Width="50"
                        Height="50"
                        Canvas.Left="350"
                        Canvas.Top="0">
                    <Button.Background>
                        <ImageBrush ImageSource="/Images/appbar.close.rest.png" Stretch="None" />
                    </Button.Background>
                </Button>
            </Canvas>
        </Grid>
    </Grid>

<!--Sample code showing usage of ApplicationBar-->
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.add.rest.png" Text="添加"  Click="Appbar_Add_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.questionmark.rest.png" Text="帮助" Click="Appbar_Help_Click"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>

完整MainPage.cs代码如下:

public partial class MainPage : PhoneApplicationPage
    {
        #region 构造器

public MainPage()
        {
            InitializeComponent();
        }

#endregion

#region Appbar 事件

#region 添加事件

private void Appbar_Add_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/XapNote;component/Add.xaml", UriKind.Relative));

#region 注销掉(测试用)
            /*
                           //0123456789012345678901234567890123456789  
            string fileName="2010_12_29_13_43_01_Woo_Gankyang-CHN.txt";
            string fileContent = "我的日记";

var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

if (!appStorage.FileExists(fileName))
            {
                using (var file = appStorage.CreateFile(fileName))
                {
                    using (var writer = new StreamWriter(file))
                    {
                        writer.WriteLine(fileContent);
                    }
                }
            }

bindList();
             * */

#endregion
        }

#endregion

#region 帮助事件

private void Appbar_Help_Click(object sender, EventArgs e)
        {
            this.helpCanvas.Visibility = Visibility.Visible;
        }

#endregion

#endregion

#region 程序加载事件

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
            string state = "";

if (settings.Contains("state"))
            {
                if (settings.TryGetValue<string>("state", out state))
                {
                    if (state == "add")
                    {
                        NavigationService.Navigate(new Uri("/Add.xaml", UriKind.Relative));
                    }

else if (state == "edit")
                    {
                        NavigationService.Navigate(new Uri("/ViewEdit.xaml", UriKind.Relative));
                    }
                }
            }

bindList();
        }

#endregion

#region ListBox绑定数据

private void bindList()
        {
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            List<Note> notes = new List<Note>();
           
            string[] fileList = appStorage.GetFileNames();

foreach (var file in fileList)
            {
                if (file != "__ApplicationSettings")
                {
                    //2010_12_30_14_02_01_ddd.txt
                    string fileFullName = file;

string year = file.Substring(0, 4);
                    string month = file.Substring(5, 2);
                    string day = file.Substring(8, 2);
                    string hour = file.Substring(11, 2);
                    string minute = file.Substring(14, 2);
                    string second = file.Substring(17, 2);
                    DateTime dateTime = new DateTime(int.Parse(year), int.Parse(month), int.Parse(day), int.Parse(hour), int.Parse(minute), int.Parse(second));
                    string dateCreated = dateTime.ToString("yyyy年MM月dd日 HH:MM:ss");
                    string fileName = file.Substring(20);

fileName = fileName.Substring(0, fileName.Length - 4);

notes.Add(new Note() { FileFullName = fileFullName, DateCreated = dateCreated, FileName = fileName });
                }
            }

noteListBox.ItemsSource = notes;
        }

#endregion

#region HyperlinkButton事件

private void noteLocation_Click(object sender, RoutedEventArgs e)
        {
            HyperlinkButton clickedLink = (HyperlinkButton)sender;
            string uri = string.Format("/XapNote;component/ViewEdit.xaml?id={0}", clickedLink.Tag);

NavigationService.Navigate(new Uri(uri, UriKind.Relative));
        }

#endregion

#region 关闭帮助事件

private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            this.helpCanvas.Visibility = Visibility.Collapsed;
        }

#endregion
    }

  二、添加日记功能

  1.Appbar_Add_Click事件,导航到Add.xaml页面

    private void Appbar_Add_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/XapNote;component/Add.xaml", UriKind.Relative));

     }

  2.Add.xaml页面

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock  Name="displayTextBlock"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"
                        Visibility="Collapsed">
            </TextBlock>
            <TextBox Name="editTextBox"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                     TextChanged="editTextBox_TextChanged">
            </TextBox>
            <Canvas Name="namedDialog"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Background="Red"
                    Margin="59,6,0,0"
                    Width="350"
                    Height="300"
                    Visibility="Collapsed">
                <TextBlock Text="请您输入日记名称"
                           Width="221"
                           Height="40"
                           TextWrapping="Wrap"
                           Canvas.Left="63"
                           Canvas.Top="27"
                           FontSize="27">
                </TextBlock>
                <TextBox   Name="fileNameTextBox"
                           Width="338"
                           Height="77"
                           TextWrapping="Wrap"
                           Canvas.Left="6"
                           Canvas.Top="97"
                           FontSize="27"
                           TextChanged="fileNameTextBox_TextChanged">
                </TextBox>
                <Button Name="btnOk"
                        Canvas.Left="0"
                        Canvas.Top="222"
                        Content="确定"
                        Width="150"
                        Click="btnOk_Click">
                </Button>
                <Button Name="btnClear"
                        Canvas.Left="194"
                        Canvas.Top="222"
                        Content="清除"
                        Width="150"
                        Click="btnClear_Click">
                </Button>
            </Canvas>

</Grid>
    </Grid>

<!--Sample code showing usage of ApplicationBar-->
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.save.rest.png" Text="保存" Click="Appbar_Save_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.cancel.rest.png" Text="取消"  Click="Appbar_Cancel_Click"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

  说明:displayTextBlock显示日记内容,editTextBox编辑日记内容,namedDialog是命名文件的对话框

  1)Appbar_Save_Click事件

      private void Appbar_Save_Click(object sender, EventArgs e)
        {
            this.displayTextBlock.Text = this.editTextBox.Text;
            this.displayTextBlock.Visibility = Visibility.Visible;
            this.editTextBox.Visibility = Visibility.Collapsed;
            this.namedDialog.Visibility = Visibility.Visible;
        }

  2)btnClear_Click事件

      private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            this.fileNameTextBox.Text = "";
        }

  3)btnOk_Click事件  

     private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.namedDialog.Visibility = Visibility.Collapsed;
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

      //构建文件全名

StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.Year);
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Month));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Day));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Hour));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Minute));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Second));
            sb.Append("_");
            sb.Append(fileName);
            sb.Append(".txt");

fileFullName = sb.ToString();

try
            {

        //创建文件  
                using (var fileStream = appStorage.OpenFile(fileFullName, FileMode.Create))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {

            //向文件中写入内容
                      writer.WriteLine(this.editTextBox.Text);
                    }
                }
            }
            catch (Exception)
            {

}

navigateBack();
        }

  例如我们输入如图信息

  

  将其保存,我们查看一下文件全名如图

  

  4)fileNameTextBox_TextChanged事件

      this.fileName = this.fileNameTextBox.Text;

  5)navigateBack()方法

     private void navigateBack()
        {

      NavigationService.Navigate(new Uri("/XapNote;component/MainPage.xaml", UriKind.Relative));
        }

  6)Appbar_Cancel_Click事件

     private void Appbar_Cancel_Click(object sender, EventArgs e)
        {
            navigateBack();
        }

  完整Add.xaml代码如下:

<phone:PhoneApplicationPage
    x:Class="XapNote.Add"
    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="PortraitOrLandscape" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="记事本" FontSize="30"/>
            <TextBlock x:Name="PageTitle" Text="添加日记" Margin="9,-7,0,0" FontSize="22" TextAlignment="Center"/>
        </StackPanel>

<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock  Name="displayTextBlock"
                        HorizontalAlignment="Stretch"
                        VerticalAlignment="Stretch"
                        Visibility="Collapsed">
            </TextBlock>
            <TextBox Name="editTextBox"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                     TextChanged="editTextBox_TextChanged">
            </TextBox>
            <Canvas Name="namedDialog"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Background="Red"
                    Margin="59,6,0,0"
                    Width="350"
                    Height="300"
                    Visibility="Collapsed">
                <TextBlock Text="请您输入日记名称"
                           Width="221"
                           Height="40"
                           TextWrapping="Wrap"
                           Canvas.Left="63"
                           Canvas.Top="27"
                           FontSize="27">
                </TextBlock>
                <TextBox   Name="fileNameTextBox"
                           Width="338"
                           Height="77"
                           TextWrapping="Wrap"
                           Canvas.Left="6"
                           Canvas.Top="97"
                           FontSize="27"
                           TextChanged="fileNameTextBox_TextChanged">
                </TextBox>
                <Button Name="btnOk"
                        Canvas.Left="0"
                        Canvas.Top="222"
                        Content="确定"
                        Width="150"
                        Click="btnOk_Click">
                </Button>
                <Button Name="btnClear"
                        Canvas.Left="194"
                        Canvas.Top="222"
                        Content="清除"
                        Width="150"
                        Click="btnClear_Click">
                </Button>
            </Canvas>

</Grid>
    </Grid>

<!--Sample code showing usage of ApplicationBar-->
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.save.rest.png" Text="保存" Click="Appbar_Save_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.cancel.rest.png" Text="取消"  Click="Appbar_Cancel_Click"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>

  完整Add.cs如下:   

public partial class Add : PhoneApplicationPage
    {
        #region 私有变量
        private string fileFullName;
        private string fileName;
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

#endregion

#region 构造器

public Add()
        {
            InitializeComponent();
        }

#endregion

#region Appbar事件

#region 保存日记事件

private void Appbar_Save_Click(object sender, EventArgs e)
        {
            this.displayTextBlock.Text = this.editTextBox.Text;
            this.displayTextBlock.Visibility = Visibility.Visible;
            this.editTextBox.Visibility = Visibility.Collapsed;
            this.namedDialog.Visibility = Visibility.Visible;
        }

#endregion

#region 取消保存日记事件

private void Appbar_Cancel_Click(object sender, EventArgs e)
        {
            navigateBack();
        }

#endregion

#endregion

#region 页面导航方法

private void navigateBack()
        {
            settings["state"] = "";
            settings["value"] = "";
            NavigationService.Navigate(new Uri("/XapNote;component/MainPage.xaml", UriKind.Relative));
        }

#endregion

#region 程序加载事件

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string state = "";

if (settings.Contains("state"))
            {
                if (settings.TryGetValue<string>("state", out state))
                {
                    if (state == "add")
                    {

string value = "";
                        if (settings.Contains("value"))
                        {
                            if (settings.TryGetValue<string>("value", out value))
                            {
                                this.editTextBox.Text = value;
                            }
                        }
                    }
                }
            }

settings["state"] = "add";
            settings["value"] = this.editTextBox.Text;
            this.editTextBox.SelectionStart = this.editTextBox.Text.Length;
            this.editTextBox.Focus();
        }

#endregion

#region editTextBox_TextChanged

private void editTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            settings["value"] = this.editTextBox.Text;
        }

#endregion

private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            this.fileNameTextBox.Text = "";
        }

private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            this.namedDialog.Visibility = Visibility.Collapsed;
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

StringBuilder sb = new StringBuilder();
            sb.Append(DateTime.Now.Year);
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Month));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Day));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Hour));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Minute));
            sb.Append("_");
            sb.Append(string.Format("{0:00}", DateTime.Now.Second));
            sb.Append("_");
            sb.Append(fileName);
            sb.Append(".txt");

fileFullName = sb.ToString();

try
            {
                using (var fileStream = appStorage.OpenFile(fileFullName, FileMode.Create))
                {
                    using (StreamWriter writer = new StreamWriter(fileStream))
                    {
                        writer.WriteLine(this.editTextBox.Text);
                    }
                }
            }
            catch (Exception)
            {

}

navigateBack();
        }

private void fileNameTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.fileName = this.fileNameTextBox.Text;
        }
    }

  四、修改日记功能

  1.ViewEdit.xaml页面

<phone:PhoneApplicationPage
    x:Class="XapNote.ViewEdit"
    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="PortraitOrLandscape" Orientation="Portrait"
    mc:Ignorable="d" d:DesignHeight="696" d:DesignWidth="480"
    shell:SystemTray.IsVisible="True" Loaded="PhoneApplicationPage_Loaded">

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="记事本" FontSize="30"/>
            <TextBlock x:Name="PageTitle" Text="编辑日记" Margin="9,-7,0,0" FontSize="22" TextAlignment="Center"/>
        </StackPanel>

<!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
            <TextBlock Name="displayTextBlock"
                       HorizontalAlignment="Stretch"
                       VerticalAlignment="Stretch"
                       Visibility="Visible"
                       TextWrapping="Wrap">
            </TextBlock>

<TextBox Name="editTextBox"
                     HorizontalAlignment="Stretch"
                     VerticalAlignment="Stretch"
                     Visibility="Collapsed"
                     TextWrapping="Wrap"
                     TextChanged="editTextBox_TextChanged"
                     >
            </TextBox>
            <Canvas Name="confirmDialog"
                    HorizontalAlignment="Left"
                    VerticalAlignment="Top"
                    Background="Red"
                    Margin="50,100,0,0"
                    Width="350"
                    Height="300"
                    Visibility="Collapsed">
                <TextBlock Text="您确定要删除这篇日记吗?"
                           Width="330"
                           Height="40"
                           TextWrapping="Wrap"
                           Canvas.Left="20"
                           Canvas.Top="87"
                           FontSize="27">
                </TextBlock>
                <Button Name="btnCancel"
                        Canvas.Left="0"
                        Canvas.Top="222"
                        Content="取消"
                        Width="150"
                        Click="btnCancel_Click">
                </Button>
                <Button Name="btnOk"
                        Canvas.Left="194"
                        Canvas.Top="222"
                        Content="确定"
                        Width="150"
                        Click="btnOk_Click">
                </Button>
            </Canvas>
        </Grid>
    </Grid>

<!--Sample code showing usage of ApplicationBar-->
    <phone:PhoneApplicationPage.ApplicationBar>
        <shell:ApplicationBar IsVisible="True" IsMenuEnabled="True">
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.back.rest.png" Text="返回" Click="Appbar_Back_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.edit.rest.png" Text="编辑" Click="Appbar_Edit_Click"/>
            <shell:ApplicationBarIconButton IconUri="/Images/appbar.save.rest.png" Text="保存" Click="Appbar_Save_Click"/>
            <shell:ApplicationBarIconButton  IconUri="/Images/appbar.delete.rest.png" Text="删除" Click="Appbar_Delete_Click"/>
        </shell:ApplicationBar>
    </phone:PhoneApplicationPage.ApplicationBar>

</phone:PhoneApplicationPage>

  2.Appbar_Edit_Click事件

    if (this.displayTextBlock.Visibility == Visibility.Visible)
            {
                bindEdit(this.displayTextBlock.Text);
            }

  3.bindEdit方法    

  private void bindEdit(string content)
        {
            this.editTextBox.Text = content;
            this.displayTextBlock.Visibility = Visibility.Collapsed;
            this.editTextBox.Visibility = Visibility.Visible;

this.editTextBox.Focus();
            this.editTextBox.SelectionStart = this.editTextBox.Text.Length;
        }

  4.ppbar_Save_Click事件

   private void Appbar_Save_Click(object sender, EventArgs e)
        {
            if (this.editTextBox.Visibility == Visibility.Visible)
            {
                var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

try
                {
                    using (var fileStream = appStorage.OpenFile(fileName, FileMode.Create))
                    {
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            writer.WriteLine(this.editTextBox.Text);
                        }
                    }
                }
                catch (Exception)
                {

}

this.displayTextBlock.Text = this.editTextBox.Text;
                this.displayTextBlock.Visibility = Visibility.Visible;
                this.editTextBox.Visibility = Visibility.Collapsed;
            }
        }

 

  五、删除日记功能

  1.Appbar_Delete_Click事件

   var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            appStorage.DeleteFile(fileName);
            this.confirmDialog.Visibility = Visibility.Collapsed;
            navigateBack();

  ViewEdit.cs完整代码

   public partial class ViewEdit : PhoneApplicationPage
    {
        #region 私有变量

private string fileName = "";
        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

#endregion

#region 构造器

public ViewEdit()
        {
            InitializeComponent();
        }

#endregion

#region Appbar事件

#region 返回主界面事件

private void Appbar_Back_Click(object sender, EventArgs e)
        {
            navigateBack();
        }

#endregion

#region 编辑日记事件

private void Appbar_Edit_Click(object sender, EventArgs e)
        {
            if (this.displayTextBlock.Visibility == Visibility.Visible)
            {
                bindEdit(this.displayTextBlock.Text);
            }
        }

#endregion

#region 保存日记事件

private void Appbar_Save_Click(object sender, EventArgs e)
        {
            if (this.editTextBox.Visibility == Visibility.Visible)
            {
                var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

try
                {
                    using (var fileStream = appStorage.OpenFile(fileName, FileMode.Create))
                    {
                        using (StreamWriter writer = new StreamWriter(fileStream))
                        {
                            writer.WriteLine(this.editTextBox.Text);
                        }
                    }
                }
                catch (Exception)
                {

}

this.displayTextBlock.Text = this.editTextBox.Text;
                this.displayTextBlock.Visibility = Visibility.Visible;
                this.editTextBox.Visibility = Visibility.Collapsed;
            }
        }

#endregion

#region 删除日记事件

private void Appbar_Delete_Click(object sender, EventArgs e)
        {
            this.confirmDialog.Visibility = Visibility.Visible;
            // navigateBack();
        }

#endregion

#endregion

#region 页面加载事件

private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            string state = "";

if (settings.Contains("state"))
            {
                if (settings.TryGetValue<string>("state", out state))
                {
                    if (state == "edit")
                    {
                        string value = "";

if (settings.Contains("fileName"))
                        {
                            if (settings.TryGetValue<string>("fileName", out value))
                            {
                                fileName = value;
                            }
                        }

if (settings.Contains("value"))
                        {
                            if (settings.TryGetValue<string>("value", out value))
                            {
                                bindEdit(value);
                            }
                        }
                    }

else
                    {
                        bindView();
                    }
                }
            }

else
            {
                bindView();
            }
        }

#endregion

#region bindView

private void bindView()
        {
            if (NavigationContext.QueryString["id"] != null)
            {
                fileName = NavigationContext.QueryString["id"];
            }

var appStorage = IsolatedStorageFile.GetUserStoreForApplication();

try
            {
                using (var file = appStorage.OpenFile(fileName, FileMode.Open))
                {
                    using (StreamReader reader = new StreamReader(file))
                    {
                        displayTextBlock.Text = reader.ReadToEnd();
                    }
                }
            }
            catch (Exception)
            {

}

}

#endregion

#region bindEdit

private void bindEdit(string content)
        {
            this.editTextBox.Text = content;
            this.displayTextBlock.Visibility = Visibility.Collapsed;
            this.editTextBox.Visibility = Visibility.Visible;

this.editTextBox.Focus();
            this.editTextBox.SelectionStart = this.editTextBox.Text.Length;

settings["state"] = "edit";
            settings["value"] = this.editTextBox.Text;
            settings["fileName"] = fileName;
        }

#endregion

#region 页面导航事件

private void navigateBack()
        {
            settings["state"] = "";
            settings["value"] = "";
            settings["fileName"] = "";
            NavigationService.Navigate(new Uri("/XapNote;component/MainPage.xaml", UriKind.Relative));
        }

#endregion

#region 取消删除事件

private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.confirmDialog.Visibility = Visibility.Collapsed;
        }

#endregion

#region 确定删除事件

private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            appStorage.DeleteFile(fileName);
            this.confirmDialog.Visibility = Visibility.Collapsed;
            navigateBack();
        }

#endregion

#region editTextBox_TextChanged

private void editTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            settings["value"] = this.editTextBox.Text;
        }

#endregion

  结束语:

    本篇随笔就讲到这里,谢谢!

  源码下载:

    点击这里下载程序源码

Windows Phone 7项目实战之记事本(二)相关推荐

  1. App项目实战之路(二):API篇

    原创文章,转载请注明:转载自Keegan小钢 并标明原文链接:http://keeganlee.me/post/practice/20160812 微信订阅号:keeganlee_me 写于2016- ...

  2. weex项目实战篇(二)

    本期六篇文章目录(可点击跳转) 一. 阿里Weex框架快速体验与环境搭建 二. weex sdk集成到Android工程 三. weex服务项目搭建 四. Weex优雅的"降级"到 ...

  3. Spring Boot + vue-element 开发个人博客项目实战教程(二十五、项目完善及扩展(前端部分))

    ⭐ 作者简介:码上言 ⭐ 代表教程:Spring Boot + vue-element 开发个人博客项目实战教程 ⭐专栏内容:零基础学Java.个人博客系统 ⭐我的文档网站:http://xyhwh- ...

  4. Qt项目实战3:二维码生成器

    qrtool项目简介 二维码(Qrcode)现在越来越常用,扫码支付.扫码添加好友.扫码乘坐公交车和地铁,我们的生活已经与二维码息息相关.这里我们使用qt软件+qrencode开源库来生成.显示.保存 ...

  5. 机器学习完整项目实战附代码(二):探索型数据分析+特征工程+建模+报告

    1. 项目背景: 1.1 项目目标: 使用提供的波士顿房屋租赁价格数据开发一个模型,该模型可以预测房屋租赁价格, 然后解释结果以找到最能预测的变量. 这是一个受监督的回归机器学习任务:给定一组包含目标 ...

  6. android圆角对话框,Android项目实战(三十二):圆角对话框Dialog

    原文: Android项目实战(三十二):圆角对话框Dialog 前言:html 项目中多处用到对话框,用系统对话框太难看,就本身写一个自定义对话框.android 对话框包括:一.圆角程序员 二.a ...

  7. App项目实战之路(四):UI篇

    原创文章,转载请注明:转载自Keegan小钢 并标明原文链接:http://keeganlee.me/post/practice/20160903 微信订阅号:keeganlee_me 写于2016- ...

  8. 菜鸟级三层框架(EF+MVC)项目实战之 系列一 EF零基础创建领域模型

    系列概述:全系列会详细介绍抽象工厂三层的搭建,以及EF高级应用和 ASP.NET MVC3.0简单应用,应用到的技术有Ef.Lambda.Linq.Interface.T4等. 由于网上对涉及到的技术 ...

  9. jsp项目开发案例_Laravel 中使用 swoole 项目实战开发案例一 (建立 swoole 和前端通信)life...

    1 开发需要环境 工欲善其事,必先利其器.在正式开发之前我们检查好需要安装的拓展,不要开发中发现这些问题,打断思路影响我们的开发效率. 安装 swoole 拓展包 安装 redis 拓展包 安装 la ...

最新文章

  1. 大科学时代,指数级增长的科学仍然拥有前所未有的朝气与活力
  2. 开源大数据周刊-2018年08月10日 第96期
  3. Hibernate Annotation中英文文档链接下载 (Hibernate 注解)
  4. mounty不可重新挂载因为先前没有完全卸载_【译】React Hooks测试完全指南
  5. 你想被推荐系统毁掉么?
  6. 调度器Quartz的简述与使用总结
  7. 阿里云人工智能ET夺肺结节诊断世界冠军
  8. 计算机第二章题库,全国计算机二级题库第二章
  9. 人类一败涂地显示服务器,人类一败涂地怎么开服务器 | 手游网游页游攻略大全...
  10. Linux应用:FTP
  11. 使用cdn和npm引入的区别_带你体验 Vue2 和 Vue3 开发组件有什么区别
  12. c语言阶乘出现负的,C语言求1到20阶乘的和,出来的是负数
  13. 字母c语言教学课件,计算机二级考试C语言辅导课件.ppt
  14. 明日之后 找不到服务器,明日之后服务器不一样怎么办_区服不同如何解决_软吧...
  15. linux下解压rar和7z压缩文件
  16. 入门之:如何在腾讯云服务器上部署自己的静态前端项目(服务器系统:centos7)
  17. 记录微信小程序获取手机号报40029错误问题
  18. Springboot物资发放管理系统
  19. 安装design compiler的教程
  20. PC实现Win10/原生安卓双系统

热门文章

  1. Digg:私人制造的时代
  2. 计算机的病毒防治教案,计算机病毒及其防治教案.doc
  3. php-fpm linux 权限,nginx/php-fpm及网站目录的权限设置
  4. ConcurrentHashMap的源码分析-transfer
  5. NonfairSync.tryAcquire
  6. Spring5的系统架构
  7. Spring-Cloud中的统一配置中心
  8. canal数据同步(canal安装)
  9. 类属性-类属性的定义及使用
  10. 循环嵌套-使用字符串运算直接输出小星星