简体   繁体   中英

Windows Phone MVVM + Prism — Convert Event to a command

I am having trouble converting an eventhandler into a command using MVVM design and the Prism toolkit.

I'm also using the WPToolkit -- the DatePicker. I need to set the ValueChanged event to a command.

Here's my code:

MainPageViewModel

_setDateOne = new DelegateCommand(delegate()
     { });

void picker1_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
{
   using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
   if (isf.FileExists("DateOne"))
       isf.DeleteFile("DateOne");
 IsolatedStorageSettings.ApplicationSettings["DateOne"] = e.NewDateTime.Value;
 IsolatedStorageSettings.ApplicationSettings.Save();
}
}

Xaml

<toolkit:DatePicker Name="picker1" ValueChanged="picker1_ValueChanged" Value="{Binding DateOne, ElementName=this, Mode=TwoWay}"/>

I know the XAML is wrong; I don't know how to do it properly, yet.

Sorry, I'm pretty newbie with programming and especially MVVM.

No need of ValueChanged event handler here, you can do procedure to save selected date in setter of DateOne :

private DateTime _dateOne;
public DateTime DateOne
{
    get { return _dateOne; }
    set
    {
        _dateOne = value;
        SaveDate(value);
        NotifyPropertyChanged("DateOne");
    }
}

SaveDate(DateTime date)
{
    using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (isf.FileExists("DateOne"))
           isf.DeleteFile("DateOne");
        IsolatedStorageSettings.ApplicationSettings["DateOne"] = date;
        IsolatedStorageSettings.ApplicationSettings.Save();
    }
}

And assuming DataContext of your page has been set properly, binding this way is enough :

<toolkit:DatePicker Name="picker1" Value="{Binding DateOne, Mode=TwoWay}"/>

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