May*_*ava 5 c# xamarin.android xamarin xamarin.forms
我正在开发一个 Xamari.Forms 应用程序,其中有一个MainPageView.Xaml和MainPageViewModel.cs,而且我在 MainPageView.Xaml 中有 stackLayout ,我在其中动态加载视图(绑定到另一个视图模型)。当MainPageViewModel.cs发生一些更改时,我必须更新绑定到视图的第二个 ViewModel 中的一些值。我现在正在使用消息中心,但每次我都无法使用消息中心,因为我必须取消订阅它,否则它会被多次调用。是否有任何优化的方法可以在不离开屏幕的情况下从另一个视图模型调用和更新一个视图模型。
你能做的就是创建一个ContentView
你自己的 callMainPageView.xaml
并给他ViewModel
as BindingContext
。
例如:
OtherView.xaml
<ContentView>
<StackLayout>
<Label Text="{Binding MyText}" />
</StackLayout>
</ContentView>
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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!");
}
}
Run Code Online (Sandbox Code Playgroud)
MainPageView.xaml
绑定到MainViewModel
<Page ....>
<Grid>
<!-- You have stuff here -->
<OtherView BindingContext="{Binding OtherVM}" />
</Grid>
</Page>
Run Code Online (Sandbox Code Playgroud)
使用此方法,您可以使用所需的绑定上下文显示自定义视图。
PS:这是未经测试的代码,只是纯粹的理论。
希望能帮助到你。
归档时间: |
|
查看次数: |
3517 次 |
最近记录: |