Search code examples
xamarin.formsbinding-context

Xamarin forms - Passing data between pages & views


I have a xamarin forms app. There are 2 classes with data, one of the pages is filling the data.

The problem is: I'm creating new view, that should use data from both classes.

The only way i'm familiar with is to set a class as a bindingContext to pass data between pages, and it's working fine with ONE class, because apparently there couldn't be 2 bindingContext at the same time.

EXAMPLE:

1st class (all the classes are filled on the previous page. just accept that they are filled)

public class Buildings : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _id;

        public string Id
        {
            get { return _id; }
            set
            {
                _id = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Id"));
            }
        }
}

2nd class

public class Flats : INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;

            private string _num;

            public string Num
            {
                get { return _num; }
                set
                {
                    _num = value;
                    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Num"));
                }
            }
    }

new view:

public partial class HouseView
    {
        private Flats _flats;
        private Buildings _buildings;
        public HouseView()
        {
            InitializeComponent();
        }

        private void HouseView_OnBindingContextChanged(object sender, EventArgs e)
        {
            var building = BindingContext as Building;
            //var flat = BindingContext as Flat;
            //_flat = flat;
            _building = building;
           var buildingInfo = await Rest.GetHouseInfo(_building.Id, _flat.Num); //function that will return info on a current house;
          // rest code
        }
    }

Maybe there is no need for binding context, because i'm just passing the parameters, not changing them in a view? I guess the solution can be pretty simple, and i cant figure it out....


Solution

  • What you are missing is understanding the concept of ViewModel, and it's relation with the views.. In this case what you need is a 3rd class (ViewModel) that handles your 2 previous class:

    public class HouseViewModel : INotifyPropertyChanged
    {
        public Flats Flats { get; set; }
        private Buildings Buildings { get; set; }     
    }
    

    Also using OnBindingContextChanged is just messy and will take some performance from your app .. try to prepare your data before on your VM, so the view knows as little as possible in how to get/handle data.