Reputation: 10234
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:
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 the Alarm.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. string message
from TimerElapsed
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.
Upvotes: 2
Views: 911
Reputation: 16926
For 1: I'd probably put the timer either ito the application or into the view locator.If you using a IoC Container (Unity for example) putting it there might be a good idea.
For 2: you can see this post for strategies handling dialogs in MVVM.
Upvotes: 0
Reputation: 8400
You can do this (and much more) with great ease using PRISM: http://compositewpf.codeplex.com/.
For 1: Create a module that can be loaded by different viewmodels as a central service that offers the alarm triggers.While composing your application, load the module and bind it with the viewmodels.
For 2: PRISM supports the so-called Interaction Requests that allow you to pop-up dialogs in from the viewmodel in a MVVM pure way (without violating the single direction dependency of the view on the viewmodel). It works like an event send to the UI. Please read the PRISM guide (also available on above link) to find concrete code examples to achieve this.
Hope that helps.
Upvotes: 1