从另一个ViewModel Xamarin.Forms更新ViewModel [英] Update ViewModel from another ViewModel Xamarin.Forms

查看:332
本文介绍了从另一个ViewModel Xamarin.Forms更新ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Xamari.Forms应用程序,其中有一个 MainPageView.Xaml MainPageViewModel.cs ,我在MainPageView.Xaml中也有stackLayout m动态加载视图(绑定到另一个视图模型).每当 MainPageViewModel.cs 中有一些更改时,我都必须更新绑定到视图的第二个ViewModel中的某些值.我现在正在使用Messaging Center,但是每次我都无法使用Messaging Center时,因为必须取消订阅,否则它将多次被调用.是否有任何优化的方法可以在不离开屏幕的情况下从另一个视图调用和更新一个视图模型.

I am working on a Xamari.Forms application in which I have a MainPageView.Xaml and MainPageViewModel.cs, also I have stackLayout inside MainPageView.Xaml where I'm loading a view (binded to another viewmodel) dynamically. I have to update some values in second ViewModel which is binded to the view when ever there are some changes in MainPageViewModel.cs. I'm using Messaging Center for that now but everytime i cannot use Messaging center because I have to Unsubscribe it else it will get called multiple times. Is there any optimized way of calling and updating one viewmodel from another without navigating away from the screen.

推荐答案

您可以做的是从您的MainPageView.xaml中创建一个ContentView调用它,并给他ViewModel作为BindingContext.

What you can do is to create a ContentView call it from you MainPageView.xaml and give him the ViewModel as BindingContext.

例如:

OtherView.xaml

<ContentView>
    <StackLayout>
        <Label Text="{Binding MyText}" />
    </StackLayout>
</ContentView>

OtherViewModel.cs

public class OtherViewModel : INotifyPropertyChanged
{
    // Do you own implementation of INotifyPropertyChanged

    private string myText;
    public string MyText
    {
       get { return this.myText; }
       set
       {
           this.myText = value;
           this.OnPropertyChanged("MyText");
       }
    }

    public OtherViewModel(string text)
    {
        this.MyText = text;
    }
}

MainViewModel.cs

public class MainViewModel: INotifyPropertyChanged
{
    // Do you own implementation of INotifyPropertyChanged

    private OtherViewModel otherVM;
    public OtherViewModel OtherVM
    {
       get { return this.otherVM; }
    }

    public MainViewModel()
    {
        // Initialize your other viewmodel
        this.OtherVM = new OtherViewModel("Hello world!");
    }
}

MainPageView.xaml绑定到MainViewModel

<Page ....>
    <Grid>
        <!-- You have stuff here -->
        <OtherView BindingContext="{Binding OtherVM}" />
    </Grid>
</Page>

使用这种方法,您可以显示具有所需绑定上下文的自定义视图.

With this method you can display your custom view with the binding context you want.

PS:这是未经测试的代码,只是纯理论.

PS: this is code hasn't been tested, it's just pure theory.

希望有帮助.

这篇关于从另一个ViewModel Xamarin.Forms更新ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆