1

I have a number of pages, each page has its own ViewModel which inherits from BaseViewModel.

On some pages there's a DatePicker control of which SelectedDate property is binding to a ReportDate property in the BaseViewModel.

However, I was just told that the DatePicker controls on these pages should be using the same date, which means if user changes the date in the control on page 1, when he navigates to page 2, page 2 should show the same date as on page 1.

My first thought would be, to replace the ReportDate with a static DateTime property, but as far as I know that this is not possible (difficult?) in Silverlight.

Or is there a better way of doing this?

Jessica
  • 2,057
  • 1
  • 15
  • 24

1 Answers1

2

I don't think it is dificult at all. here is an example

public class BaseViewModel
{
    public DateTime ReportDate
    {
        get
        {
            return ClassHelper.StaticDate;
        }
        set
        {
            ClassHelper.StaticDate = value;
            RaisePropertyChanged("ReportDate")
        }
     }
}

public static ClassHelper : IPropertyChaged
{
    private static object sync = new object();
    private static DateTime staticDate;
    public static DateTime StaticDate
    {
        get
        {
            return staticDate;
        }
        set
        {
            lock(sync)
            {
                staticDate = value;                
            }
            RaisePropertyChanged("StaticDate")
        }
    }
}

and then in the BaseViewModel subsicribe to ClassHelper.PropertyChaged event and in the handler Call RaisePropertyChaged("ReportDate").

Don't forget to unsubscribe the event in the dispose method in BaseViewModel

Of course you might need to change other thinks but this is the base Idea.

Hope that will help you.

Clemens
  • 123,504
  • 12
  • 155
  • 268
Swift
  • 1,861
  • 14
  • 17
  • See [this answer](http://stackoverflow.com/a/251668/1136211) for an explanation why `lock(this)` is bad. Better lock a private static object member. – Clemens Jul 23 '13 at 09:48
  • 1
    I know it is bad, I put it to stress the fact that it is required to treat the case of concurent change, but since you made the point I chaged it, thank you – Swift Jul 23 '13 at 09:52
  • How can you implement INotifyPropertyChanged to a static class though? – Jessica Jul 23 '13 at 23:52
  • Actually I have figured it out. Instead of using a static class, I created a singleton class to handle the notification and everything works fine now. Thanks!! – Jessica Jul 24 '13 at 00:42