I am creating an Alarm application based on MVVM Light.
The main functionality of the app is to popup an alarm messages at specific times.
I have created a view Alarm.xaml
where I create and save the tasks with alarms, a model class Task.cs
, and a viewmodel class AlarmViewModel.cs
.
Next, I have created a timer, that checks the current time against the list of tasks every half minute:
System.Timers.Timer timer;
//I am using Timer class on purpose because I want to have asynchronous behavior
private void InitTimer()
{
timer = new Timer(30000); //Check every 30 seconds
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
timer.Start();
}
private void TimerElapsed(object sender, ElapsedEventArgs e)
{
DateTime currentTime;
string message;
currentTime = e.SignalTime;
foreach (Task task in tasks)
{
if (task.AlarmTime.CompareTo(currentTime) <= 0)
{
message = string.Format("({0}) Task:\n{1}",
task.AlarmTime.ToString("dd/MMM/yy HH:mm"), task.Description);
//This message needs to pop up
}
}
}
I have two questions:
- The first is what is the best location to initialize and start the timer? Right now, the two methods written above are located in the
AlarmViewModel.cs
class, but I intend to have more than one window in my app, and therefore more viewmodels, and I want my alarm checks to occur regardless of whether theAlarm.xaml
window is open or not. I need a kind of a central place to keep the timer running for as long as the application is running. - The second question is how to make the
string message
fromTimerElapsed
event handler pop up? I want to create a separate window/control (and a corresponding viewmodel) to show the task description. But how do I make that window/control appear (i.e. pop up) if I am controlling everything from the viewmodel tier? How is orchestrating the windows? Viewmodel locator (a component inside MVVM)? How?
Thanks for all the help. Cheers.