0
votes

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?

2

2 Answers

0
votes

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>();
0
votes

if that viewmodel is datacontext of view you can do it like in this way:

await (DataContext as YourViewModel).GetDataScore(date);

But I recommend using commands without code behind:

<interactivity:Interaction.Triggers>
                    <interactivity:EventTrigger EventName="Tap">
                        <interactivity:InvokeCommandAction Command="{Binding GetDataSourceCommand, Mode=OneWay}" CommandParameter="{Binding ElementName=YourTextBox, Path=Text}" />
                    </interactivity:EventTrigger>
<interactivity:Interaction.Triggers>

and in viewmodel:

public RelayCommand<DateTime> GetDataSourceCommand
{
    get { return _getDataSourceCommand ?? (_getDataSourceCommand = new RelayCommand<DateTime>(GetDataSource)); }
}