使用DispatchTimer C#WPF增加总和

时间:2015-05-20 06:19:49

标签: c# wpf

我希望在我的一个小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;
}

1 个答案:

答案 0 :(得分:0)

目前,您的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