简体   繁体   English

Prism VM与后面的Page代码内的View绑定

[英]Prism VM binding with View within Page code behind

Using Xamarin Forms & PCL 使用Xamarin表单和PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml 我在Page.Xaml中看到了很多有关将VM与View绑定的示例和摘要。

using this block 使用这个方块

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

And what if I want to bind the view model within the page code behind (Page.cs). 还有,如果我想将视图模型绑定到(Page.cs)后面的页面代码中,该怎么办。

You can get access to ViewMode from code behind is simply by typecasting your binding context 您可以从后面的代码中访问ViewMode,只需简单地对绑定上下文进行类型转换即可。

var pageViewModel = (PageViewModel)this.BindingContext;

It works for me. 这个对我有用。

That case you have to pass the both parameter on class instantiated because you are have required two parameter in constructor.Try the below code. 在这种情况下,您必须在实例化的类上传递两个参数,因为在构造函数中需要两个参数。请尝试以下代码。

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

You just can new the viewmodel and set it to the BindingContext. 您只需新建视图模型并将其设置为BindingContext。

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

==== EDITED ==== ====编辑====

If your viewmodel is with parameter that need to dependency inject and you want to resolve it correctly. 如果您的视图模型带有需要依赖注入的参数,并且您想正确地解决它。

App.xaml.cs App.xaml.cs

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

Page.xaml.cs Page.xaml.cs

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

In my case 就我而言

I removed from page.xaml 我从page.xaml中删除

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

and inside the code Behind (page.cs) 并在后面的代码中(page.cs)

i added 我加了

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

and it worked for me 对我有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM