简体   繁体   English

如何使用MVVMCross和Xamarin.Android从ViewModel更新视图

[英]How to Update View from ViewModel using MVVMCross and Xamarin.Android

Am new to MVVMCross with xamarin.android so little struck up with a scenario. 对于使用xamarin.android的MVVMCross来说,这是一个很新的场景。 I have a fab and mvx.recyclerview inside a fragment. 我在片段中有一个fab和mvx.recyclerview。 so when i click on this fab it will make the recyclerview scroll by a row. 因此,当我点击这个工厂时,它将使Recyclerview连续滚动。

ie

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. 这是打破mvvm模式,所以MVVM Cross中有任何方法或方法,我可以用来从ViewModel收听View。

fab.click binding with ICommand => viewmodel => view=> updatescroll(). fab.click绑定与ICommand => viewmodel => view => updatescroll()。

thanks in advance. 提前致谢。

Well, since the ViewModel should not know about the View , you should not call any method of it. 好吧,既然ViewModel不应该知道View ,你就不应该调用它的任何方法。

I would propose an event in your ViewModel where your View can subscribe. 我会在ViewModel中提出一个View可以订阅的event So you call your event something like FabClickDone and your view does what ever it wants, when this event occured. 因此,当您发生此事件时,您可以将event称为FabClickDone并且您的视图会执行它想要的任何操作。 In your case scrolling. 在你的情况下滚动。

Here is an code example for your ViewModel: 以下是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: 在您的View构造函数中订阅此事件:

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(); 既然你正在使用MVVMcross,我会建议你使用一个命令来调用OnFabClickDone();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM