Create a new class file named PostEditViewModel.cs in the ViewModels folder in the MvvmCrossDemo.Core project, as shown below:
namespaceMvvmCrossDemo.Core.ViewModels{publicclassPostEditViewModel:MvxViewModel<PostViewModel> {privatereadonlyIPostService _postService;privatereadonlyIMvxNavigationService _navigationService;privateint _postId;publicPostEditViewModel(IPostService postService,IMvxNavigationService navigationService) { _postService = postService; _navigationService = navigationService; }publicoverridevoidPrepare(PostViewModel post) { // This is the first method to be called after construction _postId =post.Id; }publicoverrideasyncTaskInitialize() { // Async initialization, YEY!await base.Initialize();awaitGetPost(_postId); }#regionPost;privatePostViewModel _post;publicPostViewModel Post {get=> _post;set=>SetProperty(ref _post, value); }#endregionprivateasyncTaskGetPost(int postId) {var response =await_postService.GetPost(postId);if (response.IsSuccess) { Post =AutoMapper.Mapper.Map<PostViewModel>(response.Result); } } }}
There are a lot of similarities between the PostDetailViewModel and the PostEditViewModel. We need to receive the current post id and get the data from the APIs. But for PostEditViewModel, we need to edit the Post and pass the result to the PostListViewModel to update the UI.
Come back to check the IMvxNavigationService interface. There is an interface that can return a result to the previous ViewModel, as shown below:
Open the PostEditViewModel.cs and change the parent class of it from MvxViewModel<PostViewModel> to MvxViewModel<PostViewModel, Post>, that means it will return a result which is the Post type. Add two new commands here:
Notice that the resource will not be really updated on the server but it will be faked as if. For more details about the fake API here: https://jsonplaceholder.typicode.com.
There are two buttons to respond to the user’s action. Each of them will call the Close method but for the Cancel button, it will return a null as the result. When the user clicks the Ok button, the EditPostAsync method will post the update to the API and if the result is a success, another Close method will be called so the MvxNavigationService will close the current ViewModel and return a result to the previous ViewModel.
Then update the EditPostAsync method in the PostListViewModel.cs file to receive the result, as shown below:
Launch the App for the Android and the UWP. Now you can edit the Post. When you return to the PostListView, you should notice that the Post has been updated.
We did a lot of changes in this section. Be aware of the data context of your current controls to implement the data-binding. If you found that the command does not work well, check the data context first to make sure the command is correctly binding to the control.