我有个电话await Shell.Current.GoToAsync($"{viewPath}");
还定义了所有带有路线的页面和所有视图模型:
services.AddSingleton<MainPage>();
services.AddSingleton<ItemPage>();
services.AddSingleton<ItemsPage>();
services.AddSingleton<MainPageViewModel>();
services.AddSingleton<ItemPageViewModel>();
services.AddSingleton<ItemsPageViewModel>();
services.AddSingleton<ItemsPageModifiedViewModel>();
我的想法是用默认的ItemsPageViewModel
调用ItemsPage
,在某些情况下,我想用ItemsPageModifiedViewModel
调用ItemsPage
。是否可以覆盖BindingContext?
您可以对同一模型使用静态视图模型。
我有一个带有第1页、第2页标签的外壳。第2页有一个导航按钮。
Page1查看模型:
public class Page1ViewModel : INotifyPropertyChanged
{
public string _str;
public event PropertyChangedEventHandler PropertyChanged;
public string str
{
get
{
return _str;
}
set
{
_str = value;
OnPropertyChanged("str");
}
}
public Page1ViewModel()
{
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Page1.xaml:
<Label Text="{Binding str}"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
Page1代码背后:
public static Page1ViewModel viewmodel { get; set; }
public Page1()
{
InitializeComponent();
viewmodel = new Page1ViewModel();
viewmodel.str = "hello";
this.BindingContext = viewmodel;
}
Page2代码背后:
private async void Button_Clicked(object sender, EventArgs e)
{
Page1.viewmodel.str = "test";
await Shell.Current.GoToAsync("//Page1");
}