question

DXamDev-1756 avatar image
0 Votes"
DXamDev-1756 asked JarvanZhang-MSFT edited

Xamarin - TabbedPage with childreen content page MVVM

Hi everybody!

I have a tabbed page with its respective viewmodel where a rest service is called from that viewmodel. The moment that rest service is called and returns a response, I need to pass that response to the viewmodels of the children of the tabbed. What is the best way to do this?

dotnet-xamarin
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

The moment that rest service is called and returns a response, I need to pass that response to the viewmodels of the children of the tabbed.

Hi, DXamDev. The Xamarin.Forms MessagingCenter class implements the publish-subscribe pattern, allowing message-based communication between components that are inconvenient to link by object and type references. It supports to make a respond when the code is executed in current class.

0 Votes 0 ·

1 Answer

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered JarvanZhang-MSFT edited

Hello,​

Welcome to our Microsoft Q&A platform!

You could also use Delegate to achieve the function. Create the delegate in the TabbedPage's ViewModel class and then subscribe the event in child page's ViewModel class.

//the viewModel class of the tabbedPage
public delegate void TestEventHandler();
namespace TestApplication
{
    public class ViewModel_TabbedPge
    {
        public event TestEventHandler TestEvent;
        public async Task TestMethod()
        {
            var response = await getResponseMethod();
            if (TestEvent != null)
            {
                TestEvent();
            }
        }
    }
}
    
//the child page
public class ViewModel_Page1
{
    ViewModel_Page1 viewModel;
    ViewModel_TabbedPge viewModel_TabbedPge;

    public ViewModel_Page1(ViewModel_TabbedPge viewModel_TabbedPge)
    {
        InitializeComponent();

        viewModel = new ViewModel_Page1();
        BindingContext = viewModel;

        viewModel_TabbedPge = App.viewModel_TabbedPge;//create a global static instance of the ViewModel_TabbedPge class in the App.cs
        viewModel_TabbedPge.TestEvent += TheTestEvent;
    }

    private void TheTestEvent()
    {
        //perform the work
    }
}

Best Regards,

Jarvan Zhang


If the response is helpful, please click "Accept Answer" and upvote it.

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.