1
votes

Using Xamarin Forms & PCL

I saw a lot of examples and snippets About binding VM with View in the Page.Xaml

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).

4

4 Answers

6
votes

You can get access to ViewMode from code behind is simply by typecasting your binding context

var pageViewModel = (PageViewModel)this.BindingContext;

It works for me.

2
votes

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);
}
0
votes

In my case

I removed from page.xaml

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

and inside the code Behind (page.cs)

i added

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

and it worked for me

0
votes

You just can new the viewmodel and set it to the 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

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