【问题标题】:Prism VM binding with View within Page code behindPrism VM 与后面的页面代码中的视图绑定
【发布时间】:2017-09-27 23:06:41
【问题描述】:

使用 Xamarin 表单和 PCL

看了很多例子和sn-ps关于在Page.Xaml中绑定VM和View

使用这个块

xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
      prism:ViewModelLocator.AutowireViewModel="True"

如果我想在后面的页面代码 (Page.cs) 中绑定视图模型怎么办。

【问题讨论】:

    标签: c# xamarin xamarin.forms


    【解决方案1】:

    您可以从后面的代码中访问 ViewMode,只需对绑定上下文进行类型转换即可

    var pageViewModel = (PageViewModel)this.BindingContext;
    

    它对我有用。

    【讨论】:

      【解决方案2】:

      在这种情况下,您必须在实例化的类上传递两个参数,因为您在构造函数中需要两个参数。试试下面的代码。

       public Page()
      {
          InitializeComponent();
          this.BindingContext = new PageViewModel(Navigation,PageDialogService);
      }
      

      【讨论】:

        【解决方案3】:

        就我而言

        我从 page.xaml 中删除了

             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
          prism:ViewModelLocator.AutowireViewModel="True"
        

        和里面的代码后面(page.cs)

        我加了

            public Page()
            {
                  InitializeComponent();
                  this.BindingContext = new pageViewModel(null,null);
            }
        

        它对我有用

        【讨论】:

        • 但是您的 NavigationService 和 PageDialogServer 在视图模型中将为空
        • 我同意你的观点,在某些页面中 _navigationservice 有一个值,而在其他页面中它是 null 但仍然适用于这两种情况,我希望你能试着解释一下。
        【解决方案4】:

        您只需新建视图模型并将其设置为 BindingContext。

        public Page()
        {
            InitializeComponent();
            this.BindingContext = new MyViewModel();
        }
        

        ==== 已编辑 ====

        如果您的视图模型带有需要依赖注入的参数并且您希望正确解析它。

        App.xaml.cs

        protected override void OnInitialized()
        {
            ...
            Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<IMyViewModel, MyViewModel);
            ...
        }
        

        Page.xaml.cs

        public Page()
        {
            InitializeComponent();
            var viewModel = Microsoft.Practices.Unity.UnityContainerExtensions.Resolve<IMyViewModel>(((App)Application.Current).Container);
            this.BindingContext = viewModel;
        }
        

        【讨论】:

        • 那么如果视图模型参数是 PageViewModel(INavigationService navigationService,IPageDialogService pageDialogService) 我该怎么办
        • 在这种情况下,您需要使用依赖注入来解析 ViewModel。您可以使您的 App 类静态可访问。然后调用 App.Container.Resolve([your viewmodel type])。但在此之前,您需要通过调用 Container.RegisterType([your viewmodel type], viewmodel class) 将视图模型注册到容器中
        • 尽管我的容器是 Dryioc.Icontainer 类型,我仍然可以使用它吗?
        猜你喜欢
        • 2016-08-25
        • 2020-02-10
        • 2020-02-19
        • 2014-02-20
        • 1970-01-01
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多