WP8.1之小小记事本编程

~~~仅为自己日后参考~~~


整体手机界面:

新建记事界面(1)新建记事界面(2)编辑界面文件标题界面(1)文件标题界面(2)文件标题编辑界面
设置密码界面(1)设置密码界面(2) 屏幕快照预览关于界面密码登陆界面保存时Toast通知
 
 

一.新建笔记界面与逻辑(XAML&C#):

1.Page1.xaml

<Page
    x:Class="DelegateAndEvent.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DelegateAndEvent"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" FlowDirection="LeftToRight"  UseLayoutRounding="True"
     >
    <Page.BottomAppBar >
        <CommandBar x:Name="commandbar" Opacity="0.5" >
            <CommandBar.PrimaryCommands>
                <AppBarButton Icon="Back" Label="列表"  Click="HyperlinkButton_Click_4"></AppBarButton>
                
                <AppBarButton Label="屏幕快照" Click="ScreenSave_Click" Icon="Crop"/>
                <AppBarButton Icon="Save" Label="保存" Click="HyperlinkButton_Click_2"></AppBarButton>
                <AppBarButton x:Name="newButton" Icon="Add" Label="新建"  Click="HyperlinkButton_Click_1" >
                </AppBarButton>

            </CommandBar.PrimaryCommands>
            <CommandBar.SecondaryCommands>
                <AppBarButton Icon="Setting" Label="设置" Click="AppBarButtonSetting_Click"></AppBarButton>              
                <AppBarButton Label="预览屏幕快照" Click="PreviewScreen_Click"></AppBarButton>
                <AppBarButton Label="关于" Click="AppBarButton_Click"/>
            </CommandBar.SecondaryCommands>
        </CommandBar>
    </Page.BottomAppBar>
    <Page.Background >
        <ImageBrush Stretch="Fill" ImageSource="Assets/TitleList_bg.png" Opacity="0.5"/>
    </Page.Background>
    <Page.Resources>
        <Style x:Key="buttonStyle" TargetType="Button">
            <Setter Property="BorderThickness" Value="1.5"/>
            <Setter Property="Background" Value="Pink"/>
            <Setter Property="Margin" Value="30 10 100 0"/>
            <Setter Property="Opacity" Value="0.5"/>
        </Style>
    </Page.Resources>
    <Grid x:Name="grid1">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" ></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel x:Name="stackpanel" >
            <StackPanel Grid.Row="0" Margin="0 10" >
                <TextBlock Text="密码" TextAlignment="Center" FontSize="36"></TextBlock>
            </StackPanel >
            <StackPanel Grid.Row="1" Margin=" 0 30">
                <PasswordBox x:Name="SignPassWord" PasswordChar="♥"    IsPasswordRevealButtonEnabled="True" PlaceholderText="请在此输入密码" Height="140" FontSize="32" MaxLength="4"  Header="请输入密码"  HorizontalContentAlignment="Center"  Background="Chocolate" Opacity="0.5" PreventKeyboardDisplayOnProgrammaticFocus="True" />
            </StackPanel>
            <StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0 10" >
                <Button Content="取消" Style="{StaticResource buttonStyle}" Click="CancelButton_Click"></Button>
                <Button Content="确定" Style="{StaticResource buttonStyle}" Click="OKButton_Click"></Button>
            </StackPanel>
        </StackPanel>
        <Grid x:Name="grid"  Grid.Row="3" >
            <StackPanel>
                <TextBlock Text="记事"
                           FontSize="32"
                           FontFamily="微软雅黑"
                           HorizontalAlignment="Center"
                           Foreground="Orange"
                           Opacity="0.8"/>
                <TextBlock Text="标题"
                           FontSize="26"
                           Foreground="Cyan"
                           Margin="0"/>
                <TextBox x:Name="tb1"
                         Margin="0"
                         FontSize="32"
                         Foreground="Yellow"
                         Opacity="0.5"
                         PlaceholderText="请在此输入标题"
                         IsSpellCheckEnabled="True"
                         Background="#FF807474"
                         BorderThickness="1"
                     />
                <TextBlock Text="内容"
                           FontSize="26"
                           Foreground="Cyan"
                           Margin="0"/>
                <TextBox x:Name="tb2"             
                         Margin="0"                     
                         FontSize="24"
                         Height="500"
                         Foreground="Black"
                         Opacity="0.5"
                         TextWrapping="Wrap"
                         Background="#FFCFCACA"
                         BorderBrush="#FFF71313"
                         BorderThickness="1"
                         >
                </TextBox>
            </StackPanel>
        </Grid>
        <Grid x:Name="writeInHand_page" Grid.Row="4">
            
        </Grid>
    </Grid>
</Page>

2.Page1.xaml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.UI.Popups;
using Windows.UI;
using Windows.Storage;
using System.Threading;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using DelegateAndEvent.Common;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using Windows.Graphics.Imaging;
using Windows.Graphics.Display;
using System.Threading.Tasks;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace DelegateAndEvent
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class Page1 : Page
    {
        public Page1()
        {
            this.InitializeComponent();
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            HandleSetPassWord();

            this.navigationHelper = new NavigationHelper(this);
            navigationHelper.LoadState += navigationHelper_LoadState;
            navigationHelper.SaveState += navigationHelper_SaveState;
        }

        private NavigationHelper navigationHelper;

        public NavigationHelper NavigationHelper
        {
            get { return navigationHelper; }
            set { navigationHelper = value; }
        }

        /// <summary>
        /// 存储页面状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            try
            {
                string txt1 = tb1.Text;
                string txt2 = tb2.Text;
                e.PageState.Add("标题", txt1);
                e.PageState.Add("内容", txt2);
            }
            catch { }


        }
        /// <summary>
        /// 加载保存的页面状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            try
            {
                if (e.PageState != null)
                {
                    if (e.PageState.ContainsKey("标题") || e.PageState.ContainsKey("内容"))
                    {
                        tb1.Text = e.PageState["标题"].ToString();
                        tb2.Text = e.PageState["内容"].ToString();
                    }
                }
            }
            catch { }

        }


        /// <summary>
        /// 判断是否设置了密码
        /// </summary>
        /// <returns></returns>
        public bool isSetPassWord()
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (container.Values.ContainsKey("PassWord"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 处理设置密码
        /// </summary>
        public void HandleSetPassWord()
        {
            if (isSetPassWord() == true)
            {
                commandbar.Visibility = Visibility.Collapsed;
                grid.Visibility = Visibility.Collapsed;
                stackpanel.Visibility = Visibility.Visible;

            }
            else
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (container.Values.ContainsKey("PassWord"))
            {
                SavePassword.Key = "PassWord";
            }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            if (SavePassword.Key != null)
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                try
                {
                    StorageFolder folder = ApplicationData.Current.LocalFolder;
                    tb2.Text = await FileIO.ReadTextAsync(await folder.GetFileAsync(e.Parameter.ToString()), Windows.Storage.Streams.UnicodeEncoding.Utf8);
                    if (tb2.Text == "")
                    {
                        tb1.Text = "";
                    }
                    else
                    {
                        tb1.Text = e.Parameter.ToString();
                    }

                }
                catch { }
            }

        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {

            //导航历史
            if (this.Frame.CanGoBack)
            {
                this.Frame.GoBack();
            }
            else
            {
                this.Frame.Navigate(typeof(TitleList));
            }
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            tb1.Text = "";
            tb2.Text = "";
            tb1.Focus(FocusState.Programmatic);

        }
        //保存用户的输入
        private async void SaveTxt()
        {
            //保存数据
            //获取用户输入
            string container = tb1.Text.Trim();
            string input = tb2.Text.Trim();
            //判断用户有没有输入
            if (container.Length == 0 || input.Length == 0)
                return;
            //用户没有输入标题
            //if (container.Length == 0)
            //{
            //    //直接将内容存储到根目录
            //    ApplicationData.Current.LocalSettings.Values.Add("", input);//键:container,值:input
            //}
            //用户全都输入
            else
            {     //应用程序数据

                //ApplicationDataContainer con = ApplicationData.Current.LocalSettings;
                //    con.Values.Add(container + "      " + DateTime.Now.ToString() , input);


                //本地文件

                StorageFolder folder = ApplicationData.Current.LocalFolder;
                var file = await folder.CreateFileAsync(container, CreationCollisionOption.GenerateUniqueName);
                await FileIO.WriteTextAsync(file, "创建时间:" + DateTime.Now.ToString() + "\n" + input, Windows.Storage.Streams.UnicodeEncoding.Utf8);
                官方Toast模板02
                //<Toast>
                //     <visual>
                //        <binding template="ToastImageAndText02">
                //            <image id="1" src="img1" alt="img1"/>
                //            <text id="2">headlinetext</text>
                //            <text id="3">bodytext</text>
                //        </binding>
                //     </visual>
                //</toast>

                //创建toast模板
                XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                //往模板中添加数据
                XmlNodeList list = xml.GetElementsByTagName("text");
                list[0].AppendChild(xml.CreateTextNode("提示:"));
                list[1].AppendChild(xml.CreateTextNode("保存成功!"));
                ToastNotification notify = new ToastNotification(xml);
                ToastNotificationManager.CreateToastNotifier().Show(notify);
            }

        }
        /// <summary>
        /// 保存当前创建的文本文件并导航到TitleList页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click_2(object sender, RoutedEventArgs e)
        {

            SaveTxt();
        }
        /// <summary>
        /// 删除当前文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void HyperlinkButton_Click_4(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(TitleList));
        }

        private void AppBarButtonSetting_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(PassWord));
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (SignPassWord.Password == container.Values["PassWord"].ToString())
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                return;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Exit();
        }

        
        StorageFolder folder;
        private async void ScreenSave_Click(object sender, RoutedEventArgs e)
        {
            if (tb1.Text != "")
            {
                RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                await renderTargetBitmap.RenderAsync(this);
                IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
                folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("ScreenSave", CreationCollisionOption.OpenIfExists);
                StorageFile file = await folder.CreateFileAsync("screen.png", CreationCollisionOption.GenerateUniqueName);
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Ignore,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                         buffer.ToArray());
                    await encoder.FlushAsync();
                }
            }
            else
            {
                await  MsgShow();
                this.Opacity = 1;
            }
        }

            public async Task MsgShow()
           {
            ContentDialog  cd = new ContentDialog();
            cd.Title = "(●'◡'●)";
            cd.Opacity = 0.38;
            cd.Background = new SolidColorBrush(Colors.Red);
            cd.Foreground = new SolidColorBrush(Colors.Yellow);
            cd.Content = "请先填写标题";
            cd.Margin = new Thickness(60, 250, 0, 0);
            cd.Height = 130;
            cd.Width = 280;
            this.Opacity = 0.3;
            await cd.ShowAsync();
        }
        private void PreviewScreen_Click(object sender, RoutedEventArgs e)
        {                       
             Frame.Navigate(typeof(PreviewScreen));
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(About));
        }
    }
}

二.标题列表界面与逻辑(XAML&C#)
1.TitleList.xaml

<Page
    x:Class="DelegateAndEvent.TitleList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DelegateAndEvent"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.BottomAppBar>
        <CommandBar Opacity="0.5"
                    x:Name="cmdBar1">
            <CommandBar.PrimaryCommands >
                    <AppBarButton x:Name="selectButton4"
                              Icon="Bullets"
                              Label="选择"
                              Click="selectButton4_Click"
                              ClickMode="Release"/>

                    <AppBarButton x:Name="deleteButton5"
                              Visibility="Collapsed"
                              Icon="Delete"
                              Label="删除"
                              Click="DeleteAll_Click"/>

                    <AppBarButton x:Name="selectAllButton6"
                                  Visibility="Collapsed"
                                  Icon="SelectAll"
                                  Label="选择所有"
                                  Click="selectAll_Click"/>
                    <AppBarButton x:Name="canelButton7"
                                  Icon="Cancel"
                                  Visibility="Collapsed"
                                  Label="取消选择"
                                  Click="canelButton7_Click"/>
            </CommandBar.PrimaryCommands >
        </CommandBar>
</Page.BottomAppBar>    

                
    
    <Page.Background>
        <ImageBrush ImageSource="/Assets/Page1_bg.png"
                    Opacity="0.5"
                    Stretch="Fill"/>
    </Page.Background>

    <Grid  x:Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" ></RowDefinition>
            <RowDefinition ></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel>
            <TextBlock Text="标题"
                       Opacity="1"
                       TextAlignment="Center"
                       Margin="0"
                       Foreground="Purple"
                       FontSize="50"/>
        </StackPanel>
        <Grid x:Name="grid1" Grid.Row="1">
            <ListView x:Name="listView"                     
                     ItemsSource="{Binding Path=Collection,Mode=TwoWay}"
                     Foreground="Yellow"                     
                     FontSize="32">
                <ListView.ItemTemplate>
                    <DataTemplate >
                        <TextBlock x:Name="textBlockList"
                                   Margin="8 2 0 0"
                                   MinWidth="800"
                                   FontSize="32"
                                   Text="{Binding Path=FileName,Mode=TwoWay}"
                                   Holding="textBlockList_Holding"
                                   Tapped="textBlockList_Tapped">
                            <FlyoutBase.AttachedFlyout >
                                <MenuFlyout  >
                                    <MenuFlyoutItem Text="查看"
                                                    Foreground="Red"
                                                    Click="View_Click"/>
                                    <MenuFlyoutItem Text="删除"
                                                    Foreground="Red"
                                                    Click="Delete_Click"/>
                                </MenuFlyout>
                            </FlyoutBase.AttachedFlyout>
                        </TextBlock>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
    </Grid>
</Page>
2.TitleList.xaml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Diagnostics;
using Windows.UI.Popups;
using Windows.UI;
using Windows.Storage;
using System.Threading;
using Windows.Data.Xml.Dom;
using Windows.UI.Notifications;
using DelegateAndEvent.Common;
using Windows.UI.Xaml.Media.Imaging;
using Windows.Storage.Streams;
using Windows.Graphics.Imaging;
using Windows.Graphics.Display;
using System.Threading.Tasks;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace DelegateAndEvent
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class Page1 : Page
    {
        public Page1()
        {
            this.InitializeComponent();
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            HandleSetPassWord();

            this.navigationHelper = new NavigationHelper(this);
            navigationHelper.LoadState += navigationHelper_LoadState;
            navigationHelper.SaveState += navigationHelper_SaveState;
        }

        private NavigationHelper navigationHelper;

        public NavigationHelper NavigationHelper
        {
            get { return navigationHelper; }
            set { navigationHelper = value; }
        }

        /// <summary>
        /// 存储页面状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
        {
            try
            {
                string txt1 = tb1.Text;
                string txt2 = tb2.Text;
                e.PageState.Add("标题", txt1);
                e.PageState.Add("内容", txt2);
            }
            catch { }


        }
        /// <summary>
        /// 加载保存的页面状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            try
            {
                if (e.PageState != null)
                {
                    if (e.PageState.ContainsKey("标题") || e.PageState.ContainsKey("内容"))
                    {
                        tb1.Text = e.PageState["标题"].ToString();
                        tb2.Text = e.PageState["内容"].ToString();
                    }
                }
            }
            catch { }

        }


        /// <summary>
        /// 判断是否设置了密码
        /// </summary>
        /// <returns></returns>
        public bool isSetPassWord()
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (container.Values.ContainsKey("PassWord"))
            {
                return true;
            }
            return false;
        }

        /// <summary>
        /// 处理设置密码
        /// </summary>
        public void HandleSetPassWord()
        {
            if (isSetPassWord() == true)
            {
                commandbar.Visibility = Visibility.Collapsed;
                grid.Visibility = Visibility.Collapsed;
                stackpanel.Visibility = Visibility.Visible;

            }
            else
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedFrom(e);
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (container.Values.ContainsKey("PassWord"))
            {
                SavePassword.Key = "PassWord";
            }
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            this.navigationHelper.OnNavigatedTo(e);
            if (SavePassword.Key != null)
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                try
                {
                    StorageFolder folder = ApplicationData.Current.LocalFolder;
                    tb2.Text = await FileIO.ReadTextAsync(await folder.GetFileAsync(e.Parameter.ToString()), Windows.Storage.Streams.UnicodeEncoding.Utf8);
                    if (tb2.Text == "")
                    {
                        tb1.Text = "";
                    }
                    else
                    {
                        tb1.Text = e.Parameter.ToString();
                    }

                }
                catch { }
            }

        }

        private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
        {

            //导航历史
            if (this.Frame.CanGoBack)
            {
                this.Frame.GoBack();
            }
            else
            {
                this.Frame.Navigate(typeof(TitleList));
            }
        }

        private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
        {
            tb1.Text = "";
            tb2.Text = "";
            tb1.Focus(FocusState.Programmatic);

        }
        //保存用户的输入
        private async void SaveTxt()
        {
            //保存数据
            //获取用户输入
            string container = tb1.Text.Trim();
            string input = tb2.Text.Trim();
            //判断用户有没有输入
            if (container.Length == 0 || input.Length == 0)
                return;
            //用户没有输入标题
            //if (container.Length == 0)
            //{
            //    //直接将内容存储到根目录
            //    ApplicationData.Current.LocalSettings.Values.Add("", input);//键:container,值:input
            //}
            //用户全都输入
            else
            {     //应用程序数据

                //ApplicationDataContainer con = ApplicationData.Current.LocalSettings;
                //    con.Values.Add(container + "      " + DateTime.Now.ToString() , input);


                //本地文件

                StorageFolder folder = ApplicationData.Current.LocalFolder;
                var file = await folder.CreateFileAsync(container, CreationCollisionOption.GenerateUniqueName);
                await FileIO.WriteTextAsync(file, "创建时间:" + DateTime.Now.ToString() + "\n" + input, Windows.Storage.Streams.UnicodeEncoding.Utf8);
                官方Toast模板02
                //<Toast>
                //     <visual>
                //        <binding template="ToastImageAndText02">
                //            <image id="1" src="img1" alt="img1"/>
                //            <text id="2">headlinetext</text>
                //            <text id="3">bodytext</text>
                //        </binding>
                //     </visual>
                //</toast>

                //创建toast模板
                XmlDocument xml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);
                //往模板中添加数据
                XmlNodeList list = xml.GetElementsByTagName("text");
                list[0].AppendChild(xml.CreateTextNode("提示:"));
                list[1].AppendChild(xml.CreateTextNode("保存成功!"));
                ToastNotification notify = new ToastNotification(xml);
                ToastNotificationManager.CreateToastNotifier().Show(notify);
            }

        }
        /// <summary>
        /// 保存当前创建的文本文件并导航到TitleList页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HyperlinkButton_Click_2(object sender, RoutedEventArgs e)
        {

            SaveTxt();
        }
        /// <summary>
        /// 删除当前文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>


        private void HyperlinkButton_Click_4(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(TitleList));
        }

        private void AppBarButtonSetting_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(PassWord));
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
            if (SignPassWord.Password == container.Values["PassWord"].ToString())
            {
                commandbar.Visibility = Visibility.Visible;
                grid.Visibility = Visibility.Visible;
                stackpanel.Visibility = Visibility.Collapsed;
            }
            else
            {
                return;
            }
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            App.Current.Exit();
        }

        
        StorageFolder folder;
        private async void ScreenSave_Click(object sender, RoutedEventArgs e)
        {
            if (tb1.Text != "")
            {
                RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
                await renderTargetBitmap.RenderAsync(this);
                IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
                folder = await KnownFolders.PicturesLibrary.CreateFolderAsync("ScreenSave", CreationCollisionOption.OpenIfExists);
                StorageFile file = await folder.CreateFileAsync("screen.png", CreationCollisionOption.GenerateUniqueName);
                using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                        BitmapAlphaMode.Ignore,
                        (uint)renderTargetBitmap.PixelWidth,
                        (uint)renderTargetBitmap.PixelHeight,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                        DisplayInformation.GetForCurrentView().LogicalDpi,
                         buffer.ToArray());
                    await encoder.FlushAsync();
                }
            }
            else
            {
                await  MsgShow();
                this.Opacity = 1;
            }
        }

            public async Task MsgShow()
           {
            ContentDialog  cd = new ContentDialog();
            cd.Title = "(●'◡'●)";
            cd.Opacity = 0.38;
            cd.Background = new SolidColorBrush(Colors.Red);
            cd.Foreground = new SolidColorBrush(Colors.Yellow);
            cd.Content = "请先填写标题";
            cd.Margin = new Thickness(60, 250, 0, 0);
            cd.Height = 130;
            cd.Width = 280;
            this.Opacity = 0.3;
            await cd.ShowAsync();
        }
        private void PreviewScreen_Click(object sender, RoutedEventArgs e)
        {                       
             Frame.Navigate(typeof(PreviewScreen));
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            this.Frame.Navigate(typeof(About));
        }
    }
}
三.密码设置界面与逻辑(XAML&C#)

1.PassWord.xaml

<Page
    x:Class="DelegateAndEvent.PassWord"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DelegateAndEvent"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.Background>
        <ImageBrush ImageSource="Assets/PassWord_bg.png" Opacity="0.5"  Stretch="Fill"/>
    </Page.Background>
    <Page.Resources>
        <GridView x:Key="tb1" Opacity="0.5" Header="请输入密码" Margin="0 100 0 0" HorizontalAlignment="Center" FontSize="40">
            <GridView.Background>
                <ImageBrush ImageSource="/Assets/PassWordGridView_bg.png"  Stretch="Fill"/>
            </GridView.Background>
        <TextBox  FontSize="32" Width="300" InputScope="Number" Margin="10 200 0 0"></TextBox>
        </GridView>
        <Style x:Key="buttonStyle" TargetType="Button">
            <Setter Property="BorderThickness" Value="1.5"/>
            <Setter Property="Background" Value="Tomato"/>
            <Setter Property="Margin" Value="30 10 100 0"/>
            <Setter Property="Opacity" Value="0.5"/>
        </Style>
    </Page.Resources>
    
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0">
            <TextBlock FontSize="32" Text="设置" FontFamily="微软雅黑" TextAlignment="Center"/>
        </StackPanel>
        <StackPanel Grid.Row="1">
            <ToggleSwitch x:Name="toggleswitch" Header="设置应用程序启动时的密码"   Toggled="ToggleSwitch_Toggled">
                <FlyoutBase.AttachedFlyout>
                    <Flyout x:Name="flyout">
                        <StackPanel Height="200" Width="400" Margin="0 0 0 0"  VerticalAlignment="Center">
                            <StackPanel.Background>
                                <ImageBrush ImageSource="Assets/PassWordGridView_bg.png" Opacity="0.2"/>
                            </StackPanel.Background>
                            <PasswordBox x:Name="passWordBox" MaxLength="4" IsTextScaleFactorEnabled="True" IsPasswordRevealButtonEnabled="True" Header="请输入密码(4个字符)"  Background="DarkOrange"  Opacity="0.4"></PasswordBox>
                            <StackPanel Orientation="Horizontal">
                                <Button Content="取消" Style="{StaticResource buttonStyle}" Click="ButtonCanel_Click"></Button>
                                <Button Content="确定" Style="{StaticResource buttonStyle}" Click="ButtonOk_Click"></Button>
                            </StackPanel>
                        </StackPanel>
                    </Flyout>
                </FlyoutBase.AttachedFlyout>
            </ToggleSwitch>
        </StackPanel>
        
    </Grid>
</Page>

2.PassWord.xaml.cs

using DelegateAndEvent.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace DelegateAndEvent
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class PassWord : Page
    {
        public PassWord()
        {
            this.InitializeComponent();
            //控制回退键
            Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;

           
        }

        private  void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)
        {
          
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            try
            {
                if (SavePassword.Key != null)
                {
                    toggleswitch.IsOn = true;
                }
            }
            catch { }
        }
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
           
        }
        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
             base.OnNavigatedFrom(e);
                    
        }
        private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
        {
            try
            {
                if (((ToggleSwitch)sender).IsOn)
                {
                    flyout.ShowAt((ToggleSwitch)sender);
                    toggleswitch.IsOn = true;
                }
                else
                {
                    ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
                    container.Values.Remove("PassWord");
                }
            }
            catch { }
        }

        


        private void ButtonCanel_Click(object sender, RoutedEventArgs e)
        {
            flyout.Hide();
            toggleswitch.IsOn = false;
            return;
        }

        private async void ButtonOk_Click(object sender, RoutedEventArgs e)
        {
            if (passWordBox.Password == null||toggleswitch.IsOn==false) return;
            else
            {
                ApplicationDataContainer container = ApplicationData.Current.LocalSettings;
                 container.Values.Add("PassWord", passWordBox.Password.ToString());
               await  new MessageDialog("提示:", "设置成功").ShowAsync();
               flyout.Hide();
            }
        }
    }
}


四.关于界面UI与逻辑(XAML&C#)

1.About.xaml

<Page
    x:Class="DelegateAndEvent.About"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:DelegateAndEvent"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">    
    <Page.Resources>
        <Storyboard x:Name="storyBoard">
            <ColorAnimationUsingKeyFrames  
                Storyboard.TargetName="grid_bg"
                Storyboard.TargetProperty="Color"                
                RepeatBehavior="Forever"
                AutoReverse="True">               
                <EasingColorKeyFrame KeyTime="0:0:0" Value="AliceBlue" />
                <EasingColorKeyFrame KeyTime="0:0:05" Value="DarkGreen" />
                <EasingColorKeyFrame KeyTime="0:0:1" Value="AntiqueWhite" />
                <EasingColorKeyFrame KeyTime="0:0:15" Value="Aqua" />
                <EasingColorKeyFrame KeyTime="0:0:2" Value="Pink" />
                <EasingColorKeyFrame KeyTime="0:0:25" Value="LawnGreen" />
                <EasingColorKeyFrame KeyTime="0:0:3" Value="Aquamarine" />
            </ColorAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames  Storyboard.TargetName="myButton"
                                            Storyboard.TargetProperty="Content"
                                            AutoReverse="False"
                                            RepeatBehavior="1x"
                                            Duration="0:0:4">
                <DiscreteObjectKeyFrame  KeyTime="0:0:0" Value="H"/>
                <DiscreteObjectKeyFrame  KeyTime="0:0:05" Value="He"/>
                <DiscreteObjectKeyFrame  KeyTime="0:0:1" Value="Hel"/>
                <DiscreteObjectKeyFrame  KeyTime="0:0:15" Value="Hell"/>
                <DiscreteObjectKeyFrame  KeyTime="0:0:2" Value="Hello"/>
            </ObjectAnimationUsingKeyFrames>
            <ObjectAnimationUsingKeyFrames Storyboard.TargetName="tb_Lover"
                                           Storyboard.TargetProperty="Text"
                                           AutoReverse="False"
                                           RepeatBehavior="1x">
                <DiscreteObjectKeyFrame KeyTime="0:0:5" Value="For" ></DiscreteObjectKeyFrame>
                <DiscreteObjectKeyFrame KeyTime="0:0:6" Value="For WP Lover"></DiscreteObjectKeyFrame>
            </ObjectAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="myButton"
                                           Storyboard.TargetProperty="(Canvas.Left)"
                                           AutoReverse="False"
                                           RepeatBehavior="1x"
                                           BeginTime="0:0:2">
                <SplineDoubleKeyFrame  KeyTime="0:0:4"  Value="140"/>
            </DoubleAnimationUsingKeyFrames>
            <DoubleAnimationUsingKeyFrames Storyboard.TargetName="myButton"
                                           Storyboard.TargetProperty="(Canvas.Top)"
                                           AutoReverse="False"
                                           RepeatBehavior="1x"
                                           BeginTime="0:0:2">
                <SplineDoubleKeyFrame KeySpline="0.0,1.0,1.0,0.0"  KeyTime="0:0:4"  Value="0"/>
            </DoubleAnimationUsingKeyFrames>
            
            <DropTargetItemThemeAnimation Storyboard.TargetName="tb_Thank"
                                          Storyboard.TargetProperty="Text"
                                          BeginTime="0:0:4">               
            </DropTargetItemThemeAnimation>           
        </Storyboard>
    </Page.Resources>

    <Grid Opacity="0.5">
        <Grid.Background>
            <SolidColorBrush x:Name="grid_bg" Color="DarkGreen"/>
        </Grid.Background>
        <Canvas>
            <Button x:Name="myButton" Canvas.Top="500" FontSize="50"  BorderThickness="0"/>
            <TextBlock x:Name="tb_Thank" FontSize="32" Foreground="Cyan" Canvas.Top="90">
                <Run Text="Thank you for your using"/>
                <LineBreak/>
                <LineBreak/>
                <Run Text="                               My App"/>
            </TextBlock>
            <TextBlock x:Name="tb_Lover" FontSize="36" Foreground="Yellow" Canvas.Left="100" Canvas.Top="300"/>
            <StackPanel Canvas.Left="210" Canvas.Top="500">
                <Image x:Name="img" Source="Assets/WeChat.jpg"  MaxWidth="100" MaxHeight="100" Holding="img_Holding">
                    <FlyoutBase.AttachedFlyout>
                        <MenuFlyout x:Name="img_flyout">
                            <MenuFlyout.Items>
                                <MenuFlyoutItem Text="保存图片" Click="SavePic_Click"/>
                            </MenuFlyout.Items>
                        </MenuFlyout>
                    </FlyoutBase.AttachedFlyout>
                </Image>
                <TextBlock x:Name="Info" Canvas.Top="600" >
                    <Run Text="有任何建议,请扫描上方二维码"/>
                    <LineBreak/>
                    <Run Text="加微信详聊,谢谢!(●'◡'●)"/>
                </TextBlock>
            </StackPanel>
        </Canvas>       
    </Grid>
</Page>

2.About.xaml.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

// “空白页”项模板在 http://go.microsoft.com/fwlink/?LinkID=390556 上有介绍

namespace DelegateAndEvent
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class About : Page
    {
        public About()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// 在此页将要在 Frame 中显示时进行调用。
        /// </summary>
        /// <param name="e">描述如何访问此页的事件数据。
        /// 此参数通常用于配置页。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            storyBoard.Begin();
        }

        private  void img_Holding(object sender, HoldingRoutedEventArgs e)
        {
            img_flyout.ShowAt(img);
        }

        private async void SavePic_Click(object sender, RoutedEventArgs e)
        {
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(img, 100, 100);
            IBuffer pixelBuffer =await  renderTargetBitmap.GetPixelsAsync();
            StorageFolder folder = KnownFolders.PicturesLibrary;
            StorageFile picture =await  folder.CreateFileAsync("WeChat.png",CreationCollisionOption.OpenIfExists);
            using (var fileStream = await picture.OpenAsync(FileAccessMode.ReadWrite))
            {
                var coder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                coder.SetPixelData(BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)renderTargetBitmap.PixelWidth,
                    (uint)renderTargetBitmap.PixelHeight,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    DisplayInformation.GetForCurrentView().LogicalDpi,pixelBuffer.ToArray());

                await coder.FlushAsync();
            }
           await new MessageDialog("保存成功!","(●'◡'●)").ShowAsync();
        }
    }
}


五.标题的数据绑定

1.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace DelegateAndEvent
{
    public class TitleModel
    {

        public TitleModel(string addFileName)
        {
            this.FileName = addFileName;
        }

        public TitleModel()
        {
        
        }

        private string fileName;

        public string FileName
        {
            get
            {
                return fileName;
            }
            set
            {
                fileName = value;
                OnPropertyChanged("FileName");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged(string fileName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(fileName));
            }
        }       
    }
}

2.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace DelegateAndEvent
{
    public  class TitleViewModel
    {
        public TitleViewModel()
        {           
            
                    
        }                       
        public static async void GetFileName()
        {
            List<string> List1 = new List<string>();
            StorageFolder folder = ApplicationData.Current.LocalFolder;
            var files = await folder.GetFilesAsync();
            try
            {
                if (files.Count != 0)
                {
                    for (int i = 0; i < files.Count; i++)
                    {
                        List1.Add(files[i].Name);
                    }                    
                }
                else
                {
                    List1 = null;
                }
                    Help.OnGetFileName(List1);
            }

            catch
            {

            }
        }

        public ObservableCollection<TitleModel> Collection { get; set; }                
    }
}


VS2015中的项目截图:








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明 YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明YOLO高分设计资源源码,详情请查看资源内容中使用说明

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值