How to Update View from ViewModel using MVVMCross and Xamarin.Android
Asked Answered
M

1

8

Am new to MVVMCross with xamarin.android so little struck up with a scenario. I have a fab and mvx.recyclerview inside a fragment. so when i click on this fab it will make the recyclerview scroll by a row.

i.e

void onclick(sender object ,eventargs e)
{
   mrecyclerview.SmoothScrollToPosition(somevariable++); // do something.
}

this is breaking mvvm pattern, so is there any way or method in the MVVM Cross which i can use to listen back to the View from ViewModel.

fab.click binding with ICommand => viewmodel => view=> updatescroll().

thanks in advance.

Mezzo answered 27/4, 2016 at 17:0 Comment(0)
C
13

Well, since the ViewModel should not know about the View, you should not call any method of it.

I would propose an event in your ViewModel where your View can subscribe. So you call your event something like FabClickDone and your view does what ever it wants, when this event occured. In your case scrolling.

Here is an code example for your ViewModel:

public delegate void FabClickDoneEvent(object sender, EventArgs args);
public event FabClickDoneEvent FabClickDone;

protected virtual void OnFabClickDone()
{
    FabClickDone?.Invoke(this, EventArgs.Empty);
}

You then just call it by

void onclick(sender object , eventargs e)
{
    // Do something inside your viewmodel
    // ...
    OnFabClickDone();
}

In your View constructor subscribe to this event:

ViewModel.FabClickDone += ViewModel_FabClickDone;

And create a method where you want to do your scrolling

void ViewModel_FabClickDone(Object sender, EventArgs e)
{
    mrecyclerview.SmoothScrollToPosition(somevariable++); // do something.
}

Since you're using MVVMcross I would suggest you using a command, where you call OnFabClickDone();

Calices answered 27/4, 2016 at 17:19 Comment(4)
Probably I'm kinda late but my view constructor can't see .FabClickDone event fieldResoluble
@Resoluble - try ((MyViewModelClass)BindingContext).FabClickDone.Samaveda
... actually in mvvmcross, protected override void OnViewModelSet() { base.OnViewModelSet(); var vm = ViewModel as MyViewModelClass; vm.FabClickDone += ... }.Samaveda
You can use EventHandler delegate instead of FabClickDoneEventUrumchi

© 2022 - 2024 — McMap. All rights reserved.