Xamarin Forms - send data to previous page

I am new to Xamarin Forms. I have a Page which has a button "Choose item". On button click, it will open a new page containing a listview of items.
On clicking a particular item, I want :
1. Go back to previous page
2. Get the selected item.

I am not able to find any solution. Please help.

Answers

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    When you navigate to the new page, set its BindingContext to the same ViewModel as the first page.

    When you set the SelectedItem property of that ViewModel in Page2, Page1 has the same ViewModel, therefore it will have the new SelectedItem.

  • abhishekaggarwalabhishekaggarwal Member ✭✭

    @AdamMeaney said:
    When you navigate to the new page, set its BindingContext to the same ViewModel as the first page.

    When you set the SelectedItem property of that ViewModel in Page2, Page1 has the same ViewModel, therefore it will have the new SelectedItem.

    What if I want to return just a string, and handle it on the first page ?

  • AndreiMisiukevich_AndreiMisiukevich_ USMember ✭✭✭✭✭

    Do you use any mvvm framework?
    If no, you can pass your prev page to the next one as constructor's parameter. Or you can use MessagingCenter for sending signal

  • AdamMeaneyAdamMeaney USMember ✭✭✭✭✭

    If you don't use an MVVM framework, then events on Page2 that fire when an item is selected with the string to Page1 would work.

    But use an MVVM framework. Forms is designed around ViewModels and Binding, you should use it.

    If you had the same ViewModel object for Page1 and Page2, you just need a property of

    private string _PropertyYouWant;
    public string PropertyYouWant
    {
        get => _PropertyYouWant;
        set
        {
            _PropertyYouWant = value;
            OnPropertyChanged();
        }
    }
    

    Set it on Page 2, and wherever you need it on Page1 can bind to it as well for when you pop the page.

Sign In or Register to comment.