I'm fairly new to C# and to programming in general.
In a previous question "C# Reset a countdown timer-DispatcherTimer-" I got help to reset my timer. Then I tried to make my code more elegant and tried to create a separate class for the timer and update the countdown text block through databinding instead of hardcoding the text property in this line in timer_Tick():
Countdown.Text = (int)(duration - sw.Elapsed).TotalSeconds + " second(s)
My problem is that the binding fails. I still struggle with MVVM. Here is my code:
CountDownTimer.cs
class CountDownTimer : DispatcherTimer
{
public System.Diagnostics.Stopwatch sw { get; set; }
static readonly TimeSpan duration = TimeSpan.FromSeconds(60);
private int _seconds;
public int Seconds
{
get { return _seconds; }
set { _seconds = value; NotifyPropertyChanged("Seconds"); }
}
private string _timeElapsed;
public string TimeElapsed
{
get { return _timeElapsed; }
set { _timeElapsed = value; NotifyPropertyChanged("TimeElapsed"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public void timer_Tick(object sender, object e)
{
if (sw.Elapsed <= duration)
{
Seconds = (int)(duration - sw.Elapsed).TotalSeconds;
TimeElapsed = String.Format("{0} second(s)", Seconds);
}
else
{
TimeElapsed = "Times Up";
this.Stop();
}
}
}
EquationView.xaml
<StackPanel x:Name="timePanel" Orientation="Horizontal" Visibility="Collapsed">
<TextBlock Text="Time Left: " Height="auto"
Margin="20,10,5,10" FontSize="26"/>
<TextBlock x:Name="countdown" Text="{Binding TimeElapsed}"
Margin="20,10,20,10" Width="200"
Height="auto" FontSize="26"/>
</StackPanel>
EquationView.xaml.cs
public sealed partial class EquationView : Page
{
//code
private void startButton_Click(object sender, RoutedEventArgs e)
{
//more code
// If level == difficult enable timer
if (Level == PlayerModel.LevelEnum.Difficult)
{
// timer commands
timer.sw = System.Diagnostics.Stopwatch.StartNew();
timer.Interval = new TimeSpan(0, 0, 0, 1);
timer.Tick += timer.timer_Tick;
timer.Start();
countdown.DataContext = timer;
//more code
} //end of method
// much more code
} //end of class EquationView
I inserted the line countdown.Text = timer.TimeElapsed; to try to figure out what was off and it gave me a System.NullReferenceException. Then I changed it to timer.Seconds.ToString() the first time it showed 0 but after that it returns 56 or 57.
p.s. I retyped the property changed method from my BindableBase class because I don't want to deal with multiple inheritance right now.