Search code examples
c#windows-phone-8mvvmmvvm-lightwin-universal-app

mvvm light : call method in viewmodel from view


I am working on Universal app actually, I want to call a method in the viewmodel from the view to update the data to display.

In my viewmodel :

public async void GetDateScore(DateTime dt)
{
    string date = dt.Date.ToString("yyyyMMdd");
    List<Score> scoreList = await HtmlGetterHelper.GetLastNightScore(date);
    LastScore = new ObservableCollection<Score>();

    for (int i = 0; i < scoreList.Count; i++)
    {
        LastScore.Add(scoreList[i]);
    }
}

I try to call it with base.GetDataScore(DateTime.Today) but it doesn't work. I don't know if it's possible to call the method with something like this or if I should use the messenger of MVVM?


Solution

  • While it is my opinion, that your scenario is consequence of a wrong turn along the way, you could use the service locator to solve your problem:

    var vm = ServiceLocator.Current.GetInstance<TypeOfObject>();
    // do something with viewmodel
    

    This is possible, because MVVM Light does this ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); when it adds the ViewModelLocator file.

    for MVVM Light specifically, you can use (should behave the same as above):

    var vm = SimpleIoc.Default.GetInstance<SomeViewModel>();
    // do something with viewmodel
    

    of course you have to register it first:

    SimpleIoc.Default.Register<SomeViewModel>();