简体   繁体   中英

Two-way binding static DateTime property in Silverlight

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM