touyets
touyets

Reputation: 1325

Live countdown in MVVM project

I have a MVVM-style project (in WPF C#) where I have users add events or projects etc to a database. Each event/project they set up would have a due date (standard DD/MM/YYYY style).

In my MainViewModel, I have setup my entire ViewList and everything shows perfectly but I do not know how to have the TextBox I have created next to each project name in the view have a live countdown timer that does not use too much memory so my thinking is that this should be done at the Model level.

How can I have the model incorporate this live dynamic value if the due date is at a later date than today (so all of those that are expired do not countdown)? I would like it so that the countdown starts the second the data is called upon and not have any user action required each time they log on to the system.

Upvotes: 0

Views: 482

Answers (1)

user1228
user1228

Reputation:

Here's how I'd do it.

First, I'd expose a collection on my View Model that contained instances of a Model that contained information about each due date.

Next, I'd create a custom UserControl that encapsulated the UI for an individual element. Might have the name, maybe some other info, and also that countdown timer. It would also expose a public property for the due date. This UserControl would be used in the ItemTemplate of the ViewList. The due date property of the UserControl would be bound to the due date property of the Model.

Finally, in the codebehind of the UserControl (yes, MVVM != no codebehind!), I'd set a DispatcherTimer to fire every second that would subtract the current time from the due date and then update the UI.

You can add any other UI related logic (e.g., don't update after due, change from a countdown to static text "YOU'RE LATE", etc) in the UserControl.

I doubt there would be any issues with memory with this design.

Upvotes: 1

Related Questions