Xamarin練習的な 第1弾 二部
前回からの続きを書いて行きます。
モデルの製作ですねー。
TODO:
- + ストップウォッチ機能
- +スタート/ストップボタン
- +スタート機能
- +押したらタイムが進む
- +動いてる時は何も起こらない
- +ストップ機能
- +押したらタイムが止まる
- +止まってる時はリセットする
- +時間表示欄
- +更新して表示する
- +スタート機能
- +スタート/ストップボタン
とりあえず、ストップウォッチが必要かなーと思います。
Interfaceを定義します。
using System; namespace StopWatchGame.Model { public interface IStopWatch { string Time { get; } void Start(); void Stop(); } }
ではでは、実装をして行かないとですね。
using System; using System.Timers; namespace StopWatchGame.Model { public class SecondStopWatch : ObserverUtility.BaseObservable<string>, IStopWatch { double millSecond; Timer timer; public SecondStopWatch(int intervalMSEC){ millSecond = 0; timer = new Timer(intervalMSEC); timer.Elapsed += Timer_Elapsed; } public string Time => millSecond.ToString(); public void Start() { timer.Start(); } public void Stop() { timer.Stop(); } void Timer_Elapsed(object sender, ElapsedEventArgs e) { millSecond += timer.Interval; NotifyChanged(Time); } } }
今回は、System.Timersを使用してインターバル毎に時間を足して行き、それをObserverパターンで変更通知をだします。
では、ViewModelの方に戻ります。
ViewModelがStopWatchを使用します。
using System; using System.Windows.Input; using Xamarin.Forms; namespace StopWatchGame.ViewModel { public class StopWatchViewModel : MVVMUtility.BindableBase, IObserver<string>, IStopWatchPageViewModel { Model.SecondStopWatch stopWatch; public StopWatchViewModel() { timeText = "00:00"; stopWatch = new Model.SecondStopWatch(10); stopWatch.Subscribe(this); StartButtonCommand = new Command(() => stopWatch.Start()); StopButtonCommand = new Command(() => stopWatch.Stop()); } public string TimeText { get => timeText; set => SetProperty(ref timeText, value); } public ICommand StartButtonCommand { get; private set; } public ICommand StopButtonCommand { get; private set; } string timeText; public void OnNext(string value) { TimeText = stopWatch.Time; } public void OnCompleted() { throw new NotImplementedException(); } public void OnError(Exception error) { throw new NotImplementedException(); } } }
先ず、実際に表示する値をTimeTextに代入して行きます。
これは先ほど言ったObserverでOnNext ()でStopWatchが変更される度に呼び出されます。
あとは、StartButtonCommandとStopButtonCommandにそれぞれ処理を追加しました。
これでとりあえずは、スタート、ストップはできるようになりました。
TODO:
- + ストップウォッチ機能
- +スタート/ストップボタン
- +スタート機能
--押したらタイムが進む- +動いてる時は何も起こらない
- +ストップ機能
--押したらタイムが止まる- +止まってる時はリセットする
- +スタート機能
- +スタート/ストップボタン
- +時間表示欄
--更新して表示する- +00.00のフォーマットにする
とりあえず今日は眠いので文字書くのはここまでにします。
思ったより文字書くのに時間かかりますね笑
次はリセット機能と表示のフォーマットですねー。
ぼちぼちやって行きますのでよろしくお願いします。