ViewModel doesn't receive message in MVVM Light

倖福魔咒の 提交于 2019-12-06 04:36:48

You're right, this is not a good practice to create all view models in ViewModelLocator constructor. The reason of the issue you got is that QuestionViewModel is created after you send the message. You can try to create a service which will share current Question object and inject this service into MainViewModel and QuestionViewModel.

public interface IQuestionService
{
    Question CurrentQuestion {get; set;}
}

public class QuestionService : IQuestionService
{
    public Question CurrentQuestion {get; set;}
}

Then on Click in MainViewModel just save current question:

_questionService.CurrentQuestion = q;

and use in in your QuestionViewModel

Just make sure you inject the same instance of IQuestionService into your view models.

One more variant is to pass simple navigation arguments in a URL like this:

NavigationService.NavigateTo(new Uri("/Pages/QuestionPage.xaml?questionid=" + q.Id, UriKind.Relative));

Alternatively, you could try to implement your own NavigationService which supports passing parameters, but this is more complicated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!