トルネード

毛利のメモ書き

UWP 入門 - Binding データ更新[INotifyPropertyChanged]

下記のxamlコードはGridTextBlockを貼っただけのシンプルなコードです。 TextプロパティにBindingを書いています。

<Grid>
    <TextBlock Text="{Binding DtNow}" Loaded="TextBlock_Loaded" Name="TextBlock1"></TextBlock>
</Grid>

Text="{Binding DtNow}"部分に独自クラスをバインドさせて、クラスからのデータ更新を反映させText表示を変更させます。

独自クラス作成[TTimer]

TTimerとという名称のクラスを作成します。このクラスはタイマーインターバル毎にイベント発生させるだけのシンプルクラスです。

public class TTimer: INotifyPropertyChanged
{
    private DispatcherTimer FDispatcherTimer1;

    DateTime FDt1;

    public event PropertyChangedEventHandler PropertyChanged;

    public TTimer()
    {
        FDispatcherTimer1 = new DispatcherTimer();
        FDispatcherTimer1.Interval = new TimeSpan(0, 0, 1);//1秒間隔
        FDispatcherTimer1.Tick += do_tick;
        FDispatcherTimer1.Start();
    }
    public void do_tick(object sender, object e)
    {
        FDt1 = DateTime.Now;
        //プロパティ変更を知らせる
        PropertyChanged.Invoke(this, new PropertyChangedEventArgs("DtNow"));
    }
    public DateTime DtNow { get { return FDt1; } }
}

上記に[DtNow]というプロパティを作っています。これと、TextBlock1.TextがBindingされています。このTTimerクラスは、INotifyPropertyChangedを継承しています。これはプロパティの変更を知らせるためのPropertyChangedEventHandler PropertyChanged イベントが付いてます。

ページ側C#の実装

ページ側でLoadedイベント発生時に[TextBlock1.DataContext]にTTimerクラスのインスタンスをセットします。

private void TextBlock_Loaded(object sender, RoutedEventArgs e)
{
    TextBlock1.DataContext = new TTimer();
}

上記の処理で、Text="{Binding DtNow}"にTTimerクラスのデータ更新後TextBlock1.Textも更新されます。 f:id:mojeld:20180801152412g:plain