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>
?
說明:我們定義一個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项目实战之记事本(二)的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: java 正确使用 Volatile 变
 - 下一篇: 我的WCF之旅(13):创建基于MSMQ