SQLの窓

2013年10月10日


イラストを背景にして2ページの画面遷移を解りやすくした Windows Store テンプレート

OneDrive へ移動


MainPage

メイン画面の背景に大きなイラストを設定しました。ファイルは、『Assets フォルダ』に保存して参照しています



NextPage

次画面は、LinearGradientBrush でグラデーションにしました。



App.xaml.cs

ページの設定は、Microsoft のテンプレートを無視しました。本来の WPF と同じような形でフレーム内のコンテンツを複数ページで切り替える形にしています。
using System;
using System.Diagnostics;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Simple_Pages {

	// *************************************************
	// クラス
	// *************************************************
	sealed partial class App : Application {

		public static Frame rootFrame = null;
		public static MainPage mainPage;
		public static NextPage nextPage;

		// *************************************************
		// コンストラクタ
		// *************************************************
		public App() {
			this.InitializeComponent();
			this.Suspending += OnSuspending;
		}

		// *************************************************
		// アプリケーションがエンド ユーザーによって正常に起動された
		// *************************************************
		protected override void OnLaunched(LaunchActivatedEventArgs args) {

			// ***********************************************
			// Window => Current => Content
			// Content( Frame => Content(MainPage) )
			// ***********************************************
			// 初回は Windows 内に置く フレームを作成
			if (rootFrame == null) {
				rootFrame = new Frame();
				Window.Current.Content = rootFrame;
			}

			if (rootFrame.Content == null) {
				// メインページの初回ロード
				rootFrame.Content = new MainPage();
				// 次ページを最初に作成しておく
				nextPage = new NextPage();
			}

			// 現在のウィンドウをアクティブにします
			Window.Current.Activate();
		}

		// *************************************************
		// アプリケーションの実行が中断されたときに呼び出されます
		// *************************************************
		private void OnSuspending(object sender, SuspendingEventArgs e) {
			Debug.WriteLine("アプリケーションの実行が中断されました");

			var deferral = e.SuspendingOperation.GetDeferral();
			// アプリケーションの状態を保存してバックグラウンドの動作があれば停止します
			deferral.Complete();
		}
	}
}


MainPage.xaml

MainPage と NextPage を用意していますが、NextPage は、MainPage をコピーしてリネームしたものです。
<Page
	x:Class="Simple_Pages.MainPage"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
	xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
	xmlns:local="using:Simple_Pages"
	xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
	mc:Ignorable="d"
	Loaded="Page_Loaded">

	<!--画面定義-->
	<Grid>
		<Grid.Background>
			<ImageBrush
				ImageSource="Assets/1378650512243910.jpeg"
				Stretch="None" />
		</Grid.Background>
		<Button
			Content="次ページ"
			HorizontalAlignment="Left"
			Height="41"
			Margin="34,30,0,0"
			VerticalAlignment="Top"
			Width="136"
			Click="Button_Click_1" />
	</Grid>
	
</Page>


MainPage.xaml.cs

ページの切り替えは、Navigate メソッドを使わずに直接ページのインスタンスをセットしています。そうする為に、App クラスに参照用に static な変数を作成して、インスタンスを保存しています。
App.rootFrame.Content = App.nextPage;
※ よって、Page.OnNavigatedTo イベントは発生しません
using System;
using System.Diagnostics;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Simple_Pages {

	// *************************************************
	// クラス
	// *************************************************
	public sealed partial class MainPage : Page {

		// *************************************************
		// コンストラクタ
		// *************************************************
		public MainPage() {
			this.InitializeComponent();
			App.mainPage = this;
		}

		// *************************************************
		// ページが Frame にロードされた時に実行
		// ( アプリケーション中でページ遷移する毎 )
		// *************************************************
		private void Page_Loaded(object sender, RoutedEventArgs e) {
			Debug.WriteLine("Main Page_Loaded");
		}

		// *************************************************
		// フレームに NextPage をセット
		// *************************************************
		private void Button_Click_1(object sender, RoutedEventArgs e) {
			App.rootFrame.Content = App.nextPage;
		}


	}
}



posted by lightbox at 2013-10-10 21:05 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする

2013年08月22日


Twitter API の自分のアプリのトークンを使って投稿するだけの class VS2012_Twitter

SkyDrive に移動( Windows8 用テンプレート )

テンプレートの主な機能
❶ Twitter 投稿
❷ ダイアログボックス用クラス
❸ Http 用クラス( Twitter では無く一般的なもの )
❹ 新しいページをメモリ上に保持する為の実装( App.xaml.css )
Twitter API の自分のアプリのトークンを使って投稿するだけの class VS2010_Twitter とは、微妙に違います。 VS2012_Twitter.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Windows.Security.Cryptography;
using Windows.Security.Cryptography.Core;
using Windows.Storage.Streams;

namespace LBOX_Tool
{
	class VS2012_Twitter
	{
        private string _consumer_key;
        private string _consumer_secret;
        private string _token;
        private string _secret;

        private string _tweet_api = "https://api.twitter.com/1.1/statuses/update.json";

        public VS2012_Twitter (
            string consumer_key,
            string consumer_secret,
            string token,
            string secret
            ) {
                _consumer_key = consumer_key;
                _consumer_secret = consumer_secret;
                _token = token;
                _secret = secret;
        }

        public async Task<string> TweetAsync(string text)
        {

            // ソートされるリスト
			SortedDictionary<string, string> sd = new SortedDictionary<string, string>();
            sd.Add("oauth_consumer_key", _consumer_key);
            sd.Add("oauth_nonce", Nonce());
            sd.Add("oauth_signature_method", "HMAC-SHA1");
            sd.Add("oauth_timestamp", TimeStamp());
            sd.Add("oauth_token", _token);
            sd.Add("oauth_version", "1.0");
            sd.Add("status",  Uri.EscapeDataString(text));

            // http ヘッダ用シグネチャ作成
            string work = "";
            foreach (KeyValuePair<string, string> kvp in sd)
            {
                if (work != "")
                {
                    work += "&";
                }
                work += kvp.Key + "=" + kvp.Value;
            }

            string work2 = "";
            // メソッド
            work2 += "POST" + "&";
            // API URL
            work2 += Uri.EscapeDataString(_tweet_api) + "&";
            // Oauth + データ
            work2 += Uri.EscapeDataString(work);

            // OAuth tool チェック用
            Debug.WriteLine(work2);

            string oauth_signature = Signature(work2);

            // ヘッダ情報を作成
            work = "";
            foreach (KeyValuePair<string, string> kvp in sd)
            {
                // oauth_* のみを使用する
                if (work != "")
                {
                    if (kvp.Key.Substring(0, 6) == "oauth_") {
                        work += ", ";
                    }
                }
                if (kvp.Key.Substring(0, 6) == "oauth_")
                {
                    work += kvp.Key + "=" + Dd(kvp.Value);
                }
            }
            // シグネチャを追加( ヘッダーはソートの必要は無い )
            work += ", oauth_signature=" + Dd(Uri.EscapeDataString(oauth_signature));

            // OAuth tool チェック用
            Debug.WriteLine(work);

			string result = "";
			HttpResponseMessage response = null;
			HttpClient hc = new HttpClient();
			try
			{
				hc.MaxResponseContentBufferSize = int.MaxValue;
				hc.DefaultRequestHeaders.ExpectContinue = false;
				hc.DefaultRequestHeaders.Add("Authorization", "OAuth " + work);

				// 送信処理の準備
				HttpContent content = new FormUrlEncodedContent(new Dictionary<string, string>
                {
                    { "status",  text }
                });

				response = await hc.PostAsync( _tweet_api, content );
				result = await response.Content.ReadAsStringAsync();
				if (response.IsSuccessStatusCode)
				{
					if (result.Substring(0, 10) == "{\"errors\":")
					{
						result = "ERROR:" + response.StatusCode + ":" + result;
					}
				}
				else
				{
					result = "ERROR:" + response.StatusCode + ":2XX以外:" + result;
				}
			}
			catch (Exception ex)
			{
				result = "ERROR:" + ex.Message;
			}

			return result;

        }

        // ダブルクォートで挟む
        private string Dd(string base_string)
        {
            return "\"" + base_string + "\"";
        }

        private string Nonce()
        {
            Random rand = new Random();
            int nonce = rand.Next(1000000000);
            return nonce.ToString();
        }

        // タイムスタンプ
        private string TimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        // シグネチャ
        private string Signature(string target)
        {
			String signingKey = _consumer_secret + "&";
			signingKey += _secret;

			IBuffer keyMaterial = CryptographicBuffer.ConvertStringToBinary(signingKey, BinaryStringEncoding.Utf8);
			MacAlgorithmProvider hmacSha1Provider = MacAlgorithmProvider.OpenAlgorithm("HMAC_SHA1");
			CryptographicKey macKey = hmacSha1Provider.CreateKey(keyMaterial);
			IBuffer dataToBeSigned = CryptographicBuffer.ConvertStringToBinary(target, BinaryStringEncoding.Utf8);
			IBuffer signatureBuffer = CryptographicEngine.Sign(macKey, dataToBeSigned);
			String signature = CryptographicBuffer.EncodeToBase64String(signatureBuffer);
			return signature;
		}
	}
}


MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
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.Net.Http;
using System.Net.Http.Headers;
using System.Diagnostics;
using System.Threading.Tasks;
using LBOX_Tool;

namespace C_Sharp_Twitter1
{
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
		}

		private async void  Button_Click_1(object sender, RoutedEventArgs e)
		{
			VS2012_Twitter twitter =
				new VS2012_Twitter(
		                    "Consumer key",
		                    "Consumer secret",
		                    "Access token",
		                    "Access token secret"
				);

			string result = await twitter.TweetAsync(this.tweet.Text);
			if (result.Substring(0, 6) != "ERROR:")
			{
				this.Response.Text = result;
			}
			else
			{
				Debug.WriteLine(result);
			}

		}
	}
}

関連する記事Twitter API の自分のアプリのトークンを使って投稿するだけの class VS2010_TwitterTwitter API の自分のアプリのトークンを使って投稿するだけの class Android_TwitterWSH : VBScript と JavaScript で Twitter に投稿するTwitter アプリの登録方法と、API キーの利用PHP : Twitter 投稿関数( twitter_update ) / cURL 関数

変更履歴
2013-07-09 : 初回投稿
2013-08-22 : ダウンロード(テンプレート追加)


タグ:twitter API
posted by lightbox at 2013-08-22 15:45 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする

2013年06月30日


Win8 ストア(C#) / PDF viewer sample (Windows 8.1)

PDF viewer sample (Windows 8.1)

実行できる環境はまだ無いですが、内容は単純だったのでコメントを付けてみました。
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
//
//*********************************************************

using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using System;
using Windows.Foundation;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Automation;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Controls.Primitives;
using System.Threading.Tasks;
using Windows.Data.Pdf;

namespace PDFAPI
{	
	public sealed partial class Scenario1 : SDKTemplate.Common.LayoutAwarePage
	{
		// A pointer back to the main page.  This is needed if you want to call methods in MainPage such
		// as NotifyUser()
		// ***************************************************
		// 通知に使っていますが、機能とは関係ありません
		// ***************************************************
		MainPage rootPage = MainPage.Current;

		// ***************************************************
		// PDF を扱うクラス。インスタンスは、PdfDocument の 
		// static メソッドで取得
		// ***************************************************
		private PdfDocument _pdfDocument;   

		enum RENDEROPTIONS
		{
			NORMAL,
			ZOOM,
			PORTION
		}

		uint PDF_PAGE_INDEX = 0; //first page
		uint ZOOM_FACTOR = 3; //300% zoom
		Rect PDF_PORTION_RECT = new Rect(100, 100, 300, 400); //portion of a page
		string PDFFILENAME = "Assets\\Windows_7_Product_Guide.pdf"; //Pdf file

		public Scenario1()
		{
			this.InitializeComponent();
		}

		// ***************************************************
		// 未使用
		// ***************************************************
		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
		}

		// ***************************************************
		// ボタン毎に PDF を読み込んで簡単な加工してから表示
		// ***************************************************
		public async Task DisplayImageFileAsync(StorageFile file)
		{			
			// Display the image in the UI.
			BitmapImage src = new BitmapImage();
			src.SetSource(await file.OpenAsync(FileAccessMode.Read));
			// Image1 に表示
			Image1.Source = src;
		}

		// ***************************************************
		/// PDF ページを読み込んで、png ファイルに書き出して
		/// 加工してイメージコントロールに表示
		/// ■何故か変数名が jpgFile なのかは謎■
		// ***************************************************
		private async Task RenderPDFPage(string pdfFileName,RENDEROPTIONS renderOptions)
		{
			try
			{
				// ***************************************************
				// まずファイルとして読み込み
				// ***************************************************
				 StorageFile pdfFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(pdfFileName);
				 
				// ***************************************************
				// インスタンスを取得
				// ***************************************************
				 _pdfDocument = await PdfDocument.LoadFromFileAsync(pdfFile); ;

				if (_pdfDocument != null && _pdfDocument.PageCount > 0)
				{
					// ***************************************************
					// 最初のページを取得
					// ***************************************************
					var pdfPage = _pdfDocument.GetPage(PDF_PAGE_INDEX);					

					if (pdfPage != null)
					{
						// ***************************************************
						// 書き込み用のフォルダ
						// ***************************************************
						StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder;
										 
						// ***************************************************
						// 書き込み用のファイル
						// ***************************************************
						StorageFile jpgFile = await tempFolder.CreateFileAsync(Guid.NewGuid().ToString() + ".png", CreationCollisionOption.ReplaceExisting);
						
						if (jpgFile != null)
						{
							// ***************************************************
							// 書き込み用のファイルのストリーム( ReadWrite )
							// ***************************************************
							IRandomAccessStream randomStream = await jpgFile.OpenAsync(FileAccessMode.ReadWrite);
							
							// ***************************************************
							// 書き込み用のオプション
							// ***************************************************
							PdfPageRenderOptions pdfPageRenderOptions = new PdfPageRenderOptions();
							switch (renderOptions)
							{
								case RENDEROPTIONS.NORMAL:
									//Render Pdf page with default options
									// ***************************************************
									// 書き込み
									// ***************************************************
									await pdfPage.RenderToStreamAsync(randomStream);									
									break;
								case RENDEROPTIONS.ZOOM:
									//set PDFPageRenderOptions.DestinationWidth or DestinationHeight with expected zoom value
									Size pdfPageSize = pdfPage.Size;
									pdfPageRenderOptions.DestinationHeight = (uint)pdfPageSize.Height * ZOOM_FACTOR;
									//Render pdf page at a zoom level by passing pdfpageRenderOptions with DestinationLength set to the zoomed in length 
									// ***************************************************
									// 書き込み
									// ***************************************************
									await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);
									break;
								case RENDEROPTIONS.PORTION:
									//Set PDFPageRenderOptions.SourceRect to render portion of a page
									pdfPageRenderOptions.SourceRect = PDF_PORTION_RECT;																	 
									//Render portion of a page
									// ***************************************************
									// 書き込み
									// ***************************************************
									await pdfPage.RenderToStreamAsync(randomStream, pdfPageRenderOptions);
									break;
							}
							// ***************************************************
							// 書き込み完了
							// ***************************************************
							await randomStream.FlushAsync();
							
							// ***************************************************
							// 後始末
							// ***************************************************
							randomStream.Dispose();
							pdfPage.Dispose();

							// ***************************************************
							// 表示
							// ***************************************************
							await DisplayImageFileAsync(jpgFile);
						}
					}
				}
			}
			catch (Exception err)
			{
				rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);

			}
		}

		// ***************************************************
		// 表示ボタン1
		// ***************************************************
		private  async void RenderPage_Click(object sender, RoutedEventArgs e)
		{

			try
			{
				rootPage.NotifyUser("Rendering page...", NotifyType.StatusMessage);
			   
				await RenderPDFPage(PDFFILENAME, RENDEROPTIONS.NORMAL); 
			   
				rootPage.NotifyUser("Rendered page ", NotifyType.StatusMessage);
			}
			catch (Exception err)
			{
				rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);				
			}
		}

		// ***************************************************
		// 表示ボタン2
		// ***************************************************
		private  async void RenderPageZoom_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				rootPage.NotifyUser("Rendering page at zoom level...", NotifyType.StatusMessage);

				await RenderPDFPage(PDFFILENAME, RENDEROPTIONS.ZOOM);

				rootPage.NotifyUser("Rendered page at zoom level", NotifyType.StatusMessage);
			}
			catch (Exception err)
			{
				rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);			 
			}				
		}

		// ***************************************************
		// 表示ボタン3
		// ***************************************************
		private async void RenderPagePortion_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				rootPage.NotifyUser("Rendering portion of a page...", NotifyType.StatusMessage);

				await RenderPDFPage(PDFFILENAME, RENDEROPTIONS.PORTION);

				rootPage.NotifyUser("Rendered portion of a page ", NotifyType.StatusMessage);
			}
			catch (Exception err)
			{
				rootPage.NotifyUser("Error: " + err.Message, NotifyType.ErrorMessage);
			}					   
		 }	 
	  
	}
}




posted by lightbox at 2013-06-30 00:07 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする

2013年06月29日


ストアアプリの TextBox のスクロールバー



Metro Apps - TextBox, Scrolling

一年前の記事ですが、他にこれに相当する記事をみつけられませんでした。この記事では、コードで設定する場合、object.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto); とあるので、DependencyObject と関連すると思いますが、Microsoft の DependencyObject の説明もあまり要領を得ません。ページ遷移にしても、Navigate では元のページが破棄されてしまいますし、とても作るのが大変です。
<Page
	x:Class="App1.MainPage"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
	Loaded="Page_Loaded">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
		<Button
			x:FieldModifier="public"
			x:Name="MoveButton"
			Content="このボタンは x:FieldModifier=&quot;public&quot; です"
			HorizontalAlignment="Left"
			Height="61"
			Margin="66,64,0,0"
			VerticalAlignment="Top"
			Width="379"
			Click="MoveButton_Click" />
		<TextBox
			AcceptsReturn="True"
			Margin="66,156,729,330"
			ScrollViewer.VerticalScrollBarVisibility="Auto"
			Grid.Row="1"
			FontSize="40" />
	</Grid>
</Page>

※ ScrollViewer を親にする方法は他にいくつか見つける事ができますが、この方法を発言しているのが 
Affiliations
Microsoft Employee
となっていて、Rob Caplan さんは、Microsoft の社員さんみたいです。
posted by lightbox at 2013-06-29 14:28 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする

Win8 ストアアプリの、メモリ上にページを残す画面遷移と、前画面のコントロールの参照


▲ この画面は シミュレータの画面です

デフォルトでは、画面のコントロールは private になっているようで、x:FieldModifier="public" を設定する事によって、他のページのコードから参照可能になります( デザイナ時点で可 )
<Page
	x:Class="App1.MainPage"
	xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
	Loaded="Page_Loaded">

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
		<Button
			x:FieldModifier="public"
			x:Name="MoveButton"
			Content="このボタンは x:FieldModifier=&quot;public&quot; です"
			HorizontalAlignment="Left"
			Height="61"
			Margin="66,64,0,0"
			VerticalAlignment="Top"
			Width="379"
			Click="MoveButton_Click" />

	</Grid>
</Page>

App.xaml.cs に、ページ移動や参照用のメソッドや変数を作成しています。

❶ public static Dictionary AppPage
※ ページの実体保存用
❷ public static Frame rootFrame
※ ページの格納用( 元々ローカル変数だったものを public static に変更 )
❸ public static void PageOpen(Type name)
※ ページ移動用
❹ public static T GetPage(Type name)
※ ページ参照用

App.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
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;

namespace App1
{
    sealed partial class App : Application
    {
		public static Dictionary<Type , Page> AppPage = new Dictionary<Type , Page>();
        public static Frame rootFrame = Window.Current.Content as Frame;
		public static void PageOpen(Type name)
		{
			Page page = null;
			if (!App.AppPage.TryGetValue(name, out page))
			{
				App.rootFrame.Navigate(name);
			}
			// 2回目以降の次ページへの移動
			else
			{
				App.rootFrame.Content = App.AppPage[name];
			}
		}
		public static T GetPage<T>(Type name)
		{
			return (T)(object)App.AppPage[name];
		}

        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (rootFrame == null)
            {
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: 以前中断したアプリケーションから状態を読み込みます。
                }

                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }
            // 現在のウィンドウがアクティブであることを確認します
            Window.Current.Activate();
        }

        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: アプリケーションの状態を保存してバックグラウンドの動作があれば停止します
            deferral.Complete();
        }
    }
}


MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
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;

namespace App1
{
	public sealed partial class MainPage : Page
	{
		public MainPage()
		{
			this.InitializeComponent();

			App.AppPage.Add(typeof(MainPage), this);
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			// 画面が表示される初回だけ実行されます
			Debug.WriteLine("OnNavigatedTo");
		}

		private void MoveButton_Click(object sender, RoutedEventArgs e)
		{
			App.PageOpen(typeof(BlankPage1));
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			// 画面が表示される毎に実行されます
			Debug.WriteLine("Page_Loaded");

		}

	}
}



画面移動のたびに、画面が表示された時の処理を行うには、loaded イベント を使用します。protected override void OnNavigatedTo は、Navigate メソッド(ここでは、App.rootFrame.Navigate)が実行される最初だけ処理されます。

BlankPage1.xaml.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
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;

namespace App1
{
	public sealed partial class BlankPage1 : Page
	{
		public BlankPage1()
		{
			this.InitializeComponent();

			App.AppPage.Add(typeof(BlankPage1), this);
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			// 画面が表示される初回だけ実行されます
			Debug.WriteLine("OnNavigatedTo");
		}

		private void Button_Click_1(object sender, RoutedEventArgs e)
		{

			App.PageOpen(typeof(MainPage));

			MainPage mp = null;

			// 変数を使った参照
			mp = App.AppPage[typeof(MainPage)] as MainPage;
			Debug.WriteLine(mp.MoveButton.Content.ToString());

			// メソッドを使った参照
			mp = App.GetPage<MainPage>(typeof(MainPage));
			Debug.WriteLine(mp.MoveButton.Content.ToString());

		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			// 画面が表示される毎に実行されます
			Debug.WriteLine("Page_Loaded");
		}
	}
}

関連する記事

XAML の 各属性を別の行に配置する Visual Studio の設定



posted by lightbox at 2013-06-29 13:04 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする

2013年06月10日


Win8 ストアアプリで、『選択肢を応答するダイアログ』を簡単に使うための MessageBox クラス

MessageBox に馴染んでいる人も多いと思うので、とりあえず使うために。( MessageDialog を使うと結構面倒なので )



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;

namespace LBOX_Http
{
	class MessageBox
	{
		// **********************************************************
		// 選択肢を応答するダイアログ
		// **********************************************************
		public static async Task<bool> ShowAsync(string title, string message, UICommandInvokedHandler handler)
		{
			var messageDialog = new MessageDialog(message, title);

			// イベントを定義する
			var OK_Handler = new UICommandInvokedHandler(handler);
			var OK_Command = new UICommand("YES", OK_Handler) { Id = 0 };
			messageDialog.Commands.Add(OK_Command);

			// イベントを定義する
			var CANCEL_Handler = new UICommandInvokedHandler(handler);
			var CANCEL_Command = new UICommand("NO", CANCEL_Handler) { Id = 1 };
			messageDialog.Commands.Add(CANCEL_Command);

			// Enter キーで反応するデフォルトボタン
			messageDialog.DefaultCommandIndex = 1;
			// ESC キーで反応するキャンセルボタン
			messageDialog.CancelCommandIndex = 1;

			await messageDialog.ShowAsync();

			return true;

		}

		// **********************************************************
		// 確認をするだけのダイアログ
		// **********************************************************
		public static async Task<bool> ShowAsync(string title, string message)
		{
			var messageDialog = new MessageDialog(message, title);

			// OK ボタンのイベントを定義する
			var OK_Command = new UICommand("OK", (command) => { });
			messageDialog.Commands.Add(OK_Command);

			// Enter キーで反応するデフォルトボタン
			messageDialog.DefaultCommandIndex = 0;
			// ESC キーで反応するキャンセルボタン
			messageDialog.CancelCommandIndex = 0;

			await messageDialog.ShowAsync();

			return true;

		}

	}
}



▼ 使用方法
// *************************************************
// 保存ボタン
// *************************************************
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
	if (MyCode.Text.Trim() == "")
	{
		await MessageBox.ShowAsync("入力確認","データが入力されていません");
		return;
	}

	await MessageBox.ShowAsync("処理確認","データを保存しますか?", (IUICommand command) =>
	{
		// ボタンの応答
		if (command.Id.Equals(0))
		{
			Debug.WriteLine("YES");
		}
		if (command.Id.Equals(1))
		{
			Debug.WriteLine("NO");
		}
	});
}

ラムダ式で使用しています



posted by lightbox at 2013-06-10 20:00 | Win8 ストアアプリ | このブログの読者になる | 更新情報をチェックする
Seesaa の各ページの表示について
Seesaa の 記事がたまに全く表示されない場合があります。その場合は、設定> 詳細設定> ブログ設定 で 最新の情報に更新の『実行ボタン』で記事やアーカイブが最新にビルドされます。

Seesaa のページで、アーカイブとタグページは要注意です。タグページはコンテンツが全く無い状態になりますし、アーカイブページも歯抜けページはコンテンツが存在しないのにページが表示されてしまいます。

また、カテゴリページもそういう意味では完全ではありません。『カテゴリID-番号』というフォーマットで表示されるページですが、実際存在するより大きな番号でも表示されてしまいます。

※ インデックスページのみ、実際の記事数を超えたページを指定しても最後のページが表示されるようです

対処としては、このようなヘルプ的な情報を固定でページの最後に表示するようにするといいでしょう。具体的には、メインの記事コンテンツの下に『自由形式』を追加し、アーカイブとカテゴリページでのみ表示するように設定し、コンテンツを用意するといいと思います。


※ エキスパートモードで表示しています

アーカイブとカテゴリページはこのように簡単に設定できますが、タグページは HTML 設定を直接変更して、以下の『タグページでのみ表示される内容』の記述方法で設定する必要があります

<% if:page_name eq 'archive' -%>
アーカイブページでのみ表示される内容
<% /if %>

<% if:page_name eq 'category' -%>
カテゴリページでのみ表示される内容
<% /if %>

<% if:page_name eq 'tag' -%>
タグページでのみ表示される内容
<% /if %>
この記述は、以下の場所で使用します
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり