Mike Smith
Mike Smith

Reputation: 125

freshmvvm access PageModel from Page code behind

Im using xamarin forms with freshmvvm framework.

I would like to know how I can skip using xaml, and just access binding data from code behind in c#.

Are there any code samples that could help?

Upvotes: 5

Views: 2314

Answers (2)

Rob
Rob

Reputation: 1390

I found Gerald's answer helpful, but I found that you need to override this event in your page vs doing the as in the constructor:

protected override void OnBindingContextChanged()
{
    base.OnBindingContextChanged();

    var pageModel = BindingContext as YourFreshMVVMPageModel;

    // Modify the page based on the pageModel
}

The PageModel construction seems to take place after the page Constructor, and this Event seems to fire at the right time and still make the page do what you want.

Upvotes: 3

Gerald Versluis
Gerald Versluis

Reputation: 34013

Although this goes against the principles of MVVM there is of course a way to do it.

Without a MVVM framework you would just create a ViewModel by hand and set the BindingContext (documentation) yourself. The 'only' thing (in regard to this) a MVVM framework does for you is set that binding up automatically so you're not bothered with writing the same code over and over again.

So, imagine you have this ViewModel, note I user PageModel to match the FreshMvvm naming:

// SamplePageModel.cs
public class SamplePageModel
{
    public string Foo { get; set; } = "Bar";
}

Now in my Page, I set the BindingContext like this:

// SamplePage.cs
// ... Skipped code, just constructor here:
public SamplePage()
{
    InitializeComponent();

    BindingContext = new SamplePageModel();
}

Now you can bind to any property of SamplePageModel.

FreshMvvm does this part automagically. If, for whatever reason, you would like to access the ViewModel/PageModel directly, just do the reverse. Somewhere in your Page or code-behind you can do:

// ... Some code here
var pageModel = BindingContext as SamplePageModel;
// ... More code here

Now if pageModel isn't null there you have your data-bound and filled PageModel!

Upvotes: 7

Related Questions