Ahmed Sayed
Ahmed Sayed

Reputation: 465

Prism VM binding with View within Page code behind

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

Upvotes: 1

Views: 3082

Answers (4)

K K
K K

Reputation: 996

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.

Upvotes: 6

lowleetak
lowleetak

Reputation: 1382

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

Upvotes: 0

Ahmed Sayed
Ahmed Sayed

Reputation: 465

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

Upvotes: 0

Pratius Dubey
Pratius Dubey

Reputation: 673

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

Upvotes: 2

Related Questions