I have a Universal/Portable C# library for Windows Phone 8 and Windows 8. The library will be referenced by apps for each platform. In the library is a view model and I'm trying to put a timer in the view model. The only "Timer" available in the library for both platforms is the System.Threading.Timer (no DispatcherTimer). However, I cannot work around the cross threading issues. Is there a way to do this or do I have to create a timer in each app in the page code behind?
public class DefaultViewModel : INotifyPropertyChanged
{
System.Threading.Timer _Timer;
public DefaultViewModel()
{
this.ToggleStartStopCommand = new Command(ToggleStartStop, true);
}
private TimeSpan _Duration;
public TimeSpan Duration
{
get { return this._Duration; }
set
{
if (value != this._Duration)
{
this._Duration = value;
this.RaisePropertyChanged("Duration"); // Error occurs here
}
}
}
private bool _IsRunning;
public bool IsRunning
{
get { return this._IsRunning; }
set
{
if (value != this._IsRunning)
{
this._IsRunning = value;
this.RaisePropertyChanged("IsRunning");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (null != propertyChanged)
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public void Start()
{
this.IsRunning = true;
this._Timer = new Timer(TimerTick, this, 0, 1000);
}
private DateTime _StartTime;
public DateTime StartTime
{
get { return this._StartTime; }
set
{
if (value != this._StartTime)
{
this._StartTime = value;
this.RaisePropertyChanged("StartTime");
}
}
}
public void Stop()
{
this._Timer.Dispose();
this.IsRunning = false;
}
private void TimerTick(object o)
{
var defaultViewModel = (DefaultViewModel)o;
defaultViewModel.Duration = DateTime.Now - defaultViewModel.StartTime;
}
public void ToggleStartStop()
{
if (this.IsRunning)
this.Stop();
else
this.Start();
}
public Command ToggleStartStopCommand { get; private set; }
}