问题
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.
回答1:
What you can do is to create a ContentView call it from you MainPageView.xaml and give him the ViewModel as BindingContext.
For example:
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 binding to 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: this is code hasn't been tested, it's just pure theory.
Hope it helps.
回答2:
This is a bit of an alternative approach and I only bring this up because you mentioned that you were using the MessagingCenter but you stopped because you were getting multiple events. In this answer below I described a simple way that you can and easily subscribe and unsubscribe from events in your view model: Object disposing in Xamarin.Forms
Basically I'm building a little bit of infrastructure so that the ViewModel knows when it's appearing (to subscribe to events) and disappearing (to unsubscribe from the events) this makes sure that you don't have multiple instances of your view model in memory which would have been likely causing the multiple events you were seeing.
来源:https://stackoverflow.com/questions/43538718/update-viewmodel-from-another-viewmodel-xamarin-forms