0

I'm using a DatePicker in a WPF window and I need to execute a command to refresh the MVVM data when the user tries to open the calendar window. The DatePicker does not have a Command property.

Is there a way to accomplish this?

Thanks.

Ignacio Soler Garcia
  • 21,122
  • 31
  • 128
  • 207
  • What is it you want to do when the user opens the calendar? Surely you would normally only need to do something if (s)he actually selects a date? – Stephen Holt Feb 23 '12 at 16:42
  • I want to calculate the first and last date to be viewed on the calendar as this depends on the available data and this has to be refreshed each time the user clicks on the calendar as the application is going to run for a long time. – Ignacio Soler Garcia Feb 23 '12 at 16:47
  • 1
    Could you not achieve this by binding the DisplayDateStart and DisplayDateEnd properties of the DatePicker to relevant properties on the view model, and then updating those view model properties as and when the relevant data changes (ensuring that PropertyChanged event is raised)? – Stephen Holt Feb 23 '12 at 17:04
  • Is an option, good idea, but the fact is that the data is in a database not being polled right now, could be done but would be easier to refresh the data only on user request. But I like your idea. – Ignacio Soler Garcia Feb 23 '12 at 17:07
  • If you are afraid of the performance hit, when polling your database, remember that databinding can be asynchronously. – dowhilefor Feb 23 '12 at 17:19

2 Answers2

1

You could create an attached behavior for that or use an available framework like this to link events with commands. From that you can expose and bind your command in your viewmodel and place your update logic there.

Also this question really belongs to these kind of questions.

Community
  • 1
  • 1
dowhilefor
  • 10,971
  • 3
  • 28
  • 45
1

OK, if you really want to attach a command to an event you can use a pattern like this: http://petebarber.blogspot.com/2011/06/getting-wpf-sizechanged-events-at-start.html

Basically you define (in a separate file) an attached property which hooks up to an event. So in your case this would be the CalendarOpened event of the DatePicker. So the attached property would be called CalendarOpenedCommand and you would then use the property on your actual DatePicker like this:

<DatePicker mvvm:CalendarOpenedCommand="{Binding MyCalendarOpenedCommand}" ...

However, I personally think this is overkill if this is the only place you will use this feature. It might upset some MVVM purists, but in this case I would just put a one line event handler for CalendarOpened in the code behind, which could then call a method (or even a command if you prefer) on the view model to notify it of the calendar opening. It could then do its business and update the bound properties for DisplayDateStart and DisplayDateEnd (as I suggested in the comments above) accordingly.

Stephen Holt
  • 2,360
  • 4
  • 26
  • 34