我正在开发一个MainPageView.Xaml和MainPageViewModel.cs,的Xamari.Forms应用程序,还有一个动态加载视图(绑定到另一个视图模型)的MainPageView.Xaml内部的stackLayout。我必须更新第二个ViewModel中的一些值,当ViewModel中有一些更改时,这个值就绑定到视图中。我现在正在使用消息中心,但是每次我都不能使用消息中心,因为我必须取消订阅,否则它会被多次调用。是否有任何优化方法从另一个视图中调用和更新一个视图模型,而不从屏幕上导航。
发布于 2017-04-21 09:38:51
您可以做的是创建一个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:这是代码还没有测试,这只是纯理论。
希望能帮上忙。
发布于 2017-04-21 21:00:44
这是一种可供选择的方法,我之所以提到这一点,是因为您提到您正在使用MessagingCenter,但是您停止使用是因为您得到了多个事件。在下面的答案中,我描述了一种简单的方法,您可以轻松地订阅和取消订阅视图模型中的事件:Object disposing in Xamarin.Forms
基本上,我正在构建一些基础设施,以便ViewModel知道它何时出现(订阅事件)和消失(从事件中取消订阅)--这可以确保内存中没有视图模型的多个实例,而这些实例可能会导致所看到的多个事件。
https://stackoverflow.com/questions/43538718
复制相似问题