c# - 从另一个 ViewModel Xamarin.Forms 更新 ViewModel

标签 c# xamarin xamarin.android xamarin.forms

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

最佳答案

你可以做的是创建一个 ContentView 从你 MainPageView.xaml 调用它并给他 ViewModel 作为 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 绑定(bind)到 MainViewModel

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

使用此方法,您可以使用所需的绑定(bind)上下文显示自定义 View 。

PS:此代码未经测试,纯理论。

希望对您有所帮助。

关于c# - 从另一个 ViewModel Xamarin.Forms 更新 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538718/

相关文章:

android - Xamarin/Mono for Android - 自定义标题 View 时 AlertDialog 崩溃

listview - ContextAction MenuItem 图标在基于 Xamarin.Forms PCL 的解决方案中未显示在 iOS 平台中

c# - 通过 Xamarin.Forms 在 Android 上打印本地文件

带有 MvvmCross 的 Android splitview/region 演示器

android - 在 xamarin 表单的标签页(Android)中插入图标

c# - 多个任务完成后如何调用一个任务

c# - 用户代码未处理 invalidCastException

c# - 在 Azure 中存储媒体、视频和图像的推荐方法是什么

android - Xamarin Android 应用无法初始化 Facebook SDK

C# ??结合? : question