更新Timer for Windows商店应用程序中的分钟数

时间:2015-04-13 21:01:26

标签: c# windows visual-studio windows-phone-8 windows-store-apps

我正在尝试为我的Windows应用商店应用创建一个计时器, 我已经能够更新secondes,但不是分钟, 分钟从组合框中获取其价值

我在这里做错了什么?

  public sealed partial class MainPage : Page
  {

    int secCount = 0;
    DispatcherTimer timerCount = new DispatcherTimer();
    TextBlock time = new TextBlock();
    int m;

    public MainPage()
    {
        this.InitializeComponent();
        timerCount.Interval = new TimeSpan(0, 0, 0, 1, 0);
        timerCount.Tick += new EventHandler<object>(timer_tick);
        m = Convert.ToInt32(cMinutes.SelectedValue);
    }


    private void timer_tick(object sender, object e)
    {


        time.Text = cHours.SelectedItem + ":" + m + ":" + secCount;
        timer.Children.Add(time); //timer is the main grid


        secCount--;
        if(secCount < 0)
        {
            secCount = 59;
            m--;
        }
    }

1 个答案:

答案 0 :(得分:0)

首先,您的代码中存在一个问题,即您反复将TextBlock time添加到timer网格,并且您应该得到一个例外,抱怨TextBlock已经是Grid&#39之一小孩子。

您的问题的答案

您需要更新cMinutes&#39; SelectedValue或SelectedIndex。

一些增强功能:

我将字段timerCounttime的初始化移动到MainPage的构造函数中,最好在一个位置初始化所有字段。

由于int(secCountm)默认为0,因此您无需为整数设置初始值。

public sealed partial class MainPage : Page
{
    int secCount;
    int m;
    DispatcherTimer timerCount; //declare here, initialize in constructor
    TextBlock time; //declare here, initialize in constructor

    public MainPage()
    {
        this.InitializeComponent();

        time = new TextBlock();
        timer.Children.Add(time); //fix: only add ONCE

        //populate the Combobox
        cMinutes.Items.Add(0); 
        cMinutes.Items.Add(1);
        cMinutes.Items.Add(2);
        cMinutes.SelectedIndex = 2;

        m = Convert.ToInt32(cMinutes.SelectedValue);

        timerCount = new DispatcherTimer();
        timerCount.Interval = new TimeSpan(0, 0, 0, 1, 0);
        timerCount.Tick += new EventHandler<object>(timer_tick);
        timerCount.Start();
    }

    private void timer_tick(object sender, object e)
    {
        time.Text = cHours.SelectedItem + ":" + m + ":" + secCount;

        secCount--;
        if (secCount < 0)
        {
            secCount = 59;
            m--;

            if (cMinutes.Items.Contains(m)) //fix: update Combobox's selected value
                cMinutes.SelectedValue = m;
        }
    }
}