Search code examples
c#xamlxamarin.formsbindingtabbedpage

How to share values between pages in Tabbed page in Xamarin.Forms?


While I'm in a hospital after a surgery, having a catheter and forced to calculate a fluid intake/outflow from my body with a pencil and a sheet of paper (!!!)... I got stuck on how to share values between pages at the Tabbed page in Xamarin.Forms.

I have a page - Intake/Outflow where is an Entry element & Button element for the total intake and outflow update. User can write down an amount of fluid and hit button to add this portion to the total amount of consumed fluids. Same goes for the outflow.

My second page is an overview - the Overview page. I would like to display the total amount of fluids (Intake & Outflow) on the Overview page with two labels. That is the point where I got stuck.

I've tried to bind Label.Text to property in Overview's page viewmodel but I don't know how to update the Overview viewmodel properties from code behind of the Intake/Outflow page. I've also tried to use App's properties level which was convenient for OnSleep, OnResume rutines where I store actual values from user to further use. Again, I got stuck on an update of a label located at the Overview Page from code behind of the Intake/Outflow page. In addition, I don't know how to correctly bind the properties in XAML for App.SomeProperty which could also the problem.

The sharing of viewmodel between pages is not an option for me in this particular case.

Is my logic wrong? How should I approach to this task? Could somebody share some example with the logic described above?


Solution

  • Just use MessagingCenter, likes On OverviewViewModel

    public OverviewViewModel(){
     MessagingCenter.Subscribe<IntakeOutflowViewModel, string>(this, "LabelChanged", (sender, label)=>{
       this.LabelValue = label; // use value of label from IntakeOutflowViewModel
    })
    }
    

    And on IntakeOutflowViewModel

    public ICommand ButtonCommand => new Command(()=>{
        MessagingCenter.Send<IntakeOutflowViewModel,string>(this, "LabelChanged", LabelValue);
    })
    public string LabelValue{...,...} // The value you bind on view
    

    Hope it helps