【问题标题】:How to override ViewModel on calling a page with Shell如何在使用 Shell 调用页面时覆盖 ViewModel
【发布时间】:2021-09-19 01:08:57
【问题描述】:

我有一个电话 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>();

我的想法是调用 ItemsPage ItemsPageViewModel 这是默认的,在某些情况下我想调用 ItemsPageItemsPageModifiedViewModel 。 是否可以覆盖 BindingContext?

【问题讨论】:

    标签: c# xamarin.forms xamarin.forms.shell


    【解决方案1】:

    您可以为同一模型使用静态视图模型。

    我有一个带有 Page1、Page2 选项卡的 shell。第 2 页有一个按钮来进行导航。

    Page1ViewModel:

    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");
        }
    

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 2010-09-06
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 2021-06-16
      • 2014-12-17
      • 1970-01-01
      相关资源
      最近更新 更多