Skip to content

Instantly share code, notes, and snippets.

@Grabacr07
Last active August 29, 2015 13:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Grabacr07/9342683 to your computer and use it in GitHub Desktop.
Save Grabacr07/9342683 to your computer and use it in GitHub Desktop.
TextBlock をタイマーにするやつ。何も設定しなければ、1 秒ごとにアタッチ先 TextBlock.Text に現在時刻を設定する。Interval プロパティで更新頻度、Proc プロパティで更新時に TextBlock.Text に出力する内容を指定できる。
/// <summary>
/// <see cref="TextBlock"/> にタイマー機能を付与します。
/// </summary>
public class TimerBehavior : Behavior<TextBlock>
{
private DispatcherTimer timer;
#region Interval 依存関係プロパティ
/// <summary>
/// タイマー刻みの間隔の時間を取得または設定します。
/// </summary>
public TimeSpan Interval
{
get { return (TimeSpan)this.GetValue(IntervalProperty); }
set { this.SetValue(IntervalProperty, value); }
}
/// <summary>
/// <see cref="P:Hisol.Eos.Client.Views.Behaviors.TimerBehavior.Interval"/> 依存関係プロパティを識別します。
/// </summary>
public static readonly DependencyProperty IntervalProperty =
DependencyProperty.Register("Interval", typeof(TimeSpan), typeof(TimerBehavior), new UIPropertyMetadata(TimeSpan.FromSeconds(1), IntervalChangedCallback));
private static void IntervalChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var instance = (TimerBehavior)d;
instance.timer.Stop();
instance.timer.Interval = (TimeSpan)e.NewValue;
instance.timer.Start();
}
#endregion
#region Proc 依存関係プロパティ
/// <summary>
/// タイマーによって実行される処理を取得または設定します。
/// </summary>
public Func<string> Proc
{
get { return (Func<string>)this.GetValue(ProcProperty); }
set { this.SetValue(ProcProperty, value); }
}
/// <summary>
/// <see cref="P:Hisol.Eos.Client.Views.Behaviors.TimerBehavior.Proc"/> 依存関係プロパティを識別します。
/// </summary>
public static readonly DependencyProperty ProcProperty =
DependencyProperty.Register("Proc", typeof(Func<string>), typeof(TimerBehavior), new UIPropertyMetadata(null));
#endregion
protected override void OnAttached()
{
base.OnAttached();
this.Initialize();
this.Start();
}
protected override void OnDetaching()
{
base.OnDetaching();
this.Stop();
this.timer.Tick -= this.Tick;
}
protected virtual void Initialize()
{
if (this.timer != null) return;
this.timer = new DispatcherTimer(DispatcherPriority.Normal)
{
Interval = this.Interval
};
this.timer.Tick += this.Tick;
}
protected virtual void Start()
{
this.timer.Start();
}
protected virtual void Stop()
{
this.timer.Stop();
}
protected virtual void Tick(object sender, EventArgs e)
{
this.AssociatedObject.Text = this.Proc == null
? DateTime.Now.ToShortTimeString()
: this.Proc();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment