Search code examples
mvvmxamarinxamarin.formsfreshmvvm

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?


Solution

  • 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!