Search code examples
c#windowsvisual-studiowindows-phone-8windows-store-apps

Updating minutes in a Timer for Windows store app


I'm trying to create a timer for my windows store app, I've been able to update secondes,but not minutes, minutes gets its value from a combobox

What I'm doing wrong here?

  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--;
        }
    }

Solution

  • First there is an issue in your code, you are adding the TextBlock time to the timer Grid repeatedly, and you should get an exception complaining that the TextBlock is already one of the Grid's children.

    The answer to your question

    You need to update cMinutes' SelectedValue or SelectedIndex.

    Some enhancements:

    I move the initialization of the fields timerCount and time into the MainPage's constructor, it is a good practice to initialize all the fields in one place.

    Since int (secCount and m) is default to 0, you don't need to set the initial values for ints.

    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;
            }
        }
    }