【问题标题】:Update ViewModel from another ViewModel Xamarin.Forms从另一个 ViewModel Xamarin.Forms 更新 ViewModel
【发布时间】:2017-04-21 09:18:47
【问题描述】:

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

【问题讨论】:

    标签: c# xamarin xamarin.android xamarin.forms


    【解决方案1】:

    您可以做的是创建一个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 绑定到MainViewModel

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

    使用此方法,您可以使用所需的绑定上下文显示自定义视图。

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

    希望对你有帮助。

    【讨论】:

    • OtherViewModel需要MainViewModel的数据的情况下也会失败
    【解决方案2】:

    这是一种替代方法,我之所以提出这个只是因为您提到您正在使用 MessagingCenter,但您因为收到多个事件而停止了。在下面的这个答案中,我描述了一种简单的方法,您可以轻松地订阅和取消订阅视图模型中的事件: Object disposing in Xamarin.Forms

    基本上,我正在构建一些基础架构,以便 ViewModel 知道它何时出现(订阅事件)和消失(取消订阅事件),这确保您没有多个视图实例内存中的模型可能会导致您看到的多个事件。

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多