Windows Phone 7项目实战之记事本(二)
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>
     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));
        }
{
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事件
appStorage.DeleteFile(fileName);
this.confirmDialog.Visibility = Visibility.Collapsed;
navigateBack();
ViewEdit.cs完整代码
{
#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
结束语:
本篇随笔就讲到这里,谢谢!
源码下载:
点击这里下载程序源码
                    
                
                
            
        
浙公网安备 33010602011771号