使用DispatchTimer增加一个总和
本文关键字:一个 DispatchTimer 增加 使用 | 更新日期: 2023-09-27 17:49:46
我想在一个小WPF应用程序中每秒增加一个DispatchTimer总数。基本上,每一秒钟,这个数字就需要增加0.095美分。然后需要在标签中显示运行总数。我想我有正确的公式,但我不确定我如何得到grandTotal显示和更新每秒,一些帮助将不胜感激。
public MainWindow()
{
InitializeComponent();
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
decimal costperSec = 0.095703125m;
decimal total = costperSec + costperSec;
decimal grandTotal = decimal.Add(total, costperSec);
// Forcing the CommandManager to raise the RequerySuggested event
CommandManager.InvalidateRequerySuggested();
lblSeconds.Content = grandTotal;
//For testing
//lblSeconds.Content = "-" + "$" + DateTime.Now.Second;
}
目前,您的grandTotal仅"存储"在dispatchTimer_Tick方法范围内。
你需要做的是,将变量保存在作用域之外:
private decimal grandTotal = 0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
decimal costperSec = 0.095703125m;
decimal total = costperSec + costperSec;
grandTotal += decimal.Add(total, costperSec);
// Forcing the CommandManager to raise the RequerySuggested event
CommandManager.InvalidateRequerySuggested();
lblSeconds.Content = grandTotal;
//For testing
//lblSeconds.Content = "-" + "$" + DateTime.Now.Second;
}
作用域在编程中很常见。尤其是类c语言。以下是一些关于范围界定的基本知识:http://www.tutorialspoint.com/cprogramming/c_scope_rules.htm