我正在开发一个 Xamari.Forms 应用程序,其中有一个 MainPageView.Xaml 和 MainPageViewModel.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/