Windows Phone アプリにチャレンジしてみた。
IS12T 購入をきっかけに Windows Phone アプリにチャレンジしてみました。ネタ元は Code Recipe の以下の記事です。
10 行でズバリ!! C# Windows Phone 7 タイマーを使ったアプリケーションの開発
チュートリアルどおり作っても面白くないので、コードビハインドから MVVM にしてみます。まず ViewModel。Date と Time の二つのプロパティを用意し、DispatcherTimer の Tick イベントで1秒ごとに設定します。
using System; using System.ComponentModel; using System.Windows.Threading; namespace WP7Clock { public class ViewModel : INotifyPropertyChanged { private DispatcherTimer _timer = new DispatcherTimer(); public ViewModel() { _timer.Interval = TimeSpan.FromSeconds(1); _timer.Tick += (sender, e) => { this.Date = DateTime.Now.ToShortDateString(); this.Time = DateTime.Now.ToLongTimeString(); }; _timer.Start(); } #region Date変更通知プロパティ private string _Date; public string Date { get { return _Date; } set { if (_Date == value) return; _Date = value; OnPropertyChanged("Date"); } } #endregion #region Time変更通知プロパティ private string _Time; public string Time { get { return _Time; } set { if (_Time == value) return; _Time = value; OnPropertyChanged("Time"); } } #endregion #region INotifyPropertyChanged メンバ public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string name) { if (PropertyChanged == null) return; PropertyChanged(this, new PropertyChangedEventArgs(name)); } #endregion } }
XAML です。PhoneApplicationPage.DataContext に ViewModel を指定し、TextBlock の Text にバインドさせます。
<phone:PhoneApplicationPage x:Class="WP7Clock.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" xmlns:local="clr-namespace:WP7Clock" mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="PortraitOrLandscape" Orientation="Portrait" shell:SystemTray.IsVisible="True"> <phone:PhoneApplicationPage.DataContext> <local:ViewModel /> </phone:PhoneApplicationPage.DataContext> <!--LayoutRoot は、すべてのページ コンテンツが配置されるルート グリッドです--> <Grid x:Name="LayoutRoot" Background="Transparent"> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBlock FontSize="82" TextAlignment="Center" Text="{Binding Date, Mode=OneWay}" /> <TextBlock FontSize="100" TextAlignment="Center" Text="{Binding Time, Mode=OneWay}" /> </StackPanel> </Grid> </phone:PhoneApplicationPage>
で、実行するとエミュレーターが起動して、こうなる。
こんな感じで、まずは簡単なサンプルたくさん作りながら習得してこうと思います。しばらく Windows Phone の記事が続くかも。。。