0

I have a page and it's binding context is set to SampleViewModel. There I have a list of items (actually an ObservableCollection). Each of those items has an add to cart button. When clicked on that add to cart button,

  1. I add that item to a new ObservableCollection as CartItemsList

  2. I update a bool property item.HasAddedToCart = true.

  3. And I increase CartItemsCount by 1.

Then after adding several items to the cart like that, I navigate to the Cart Page. In the Cart Page. I need to show that CartItemsList and the CartItemsCount.

As my ViewModel (SampleViewModel) already has those CartItemsList and the CartItemsCount I thought setting the Cart page's binding context to the same viewmodel instance. But when I set the binding context in XAML it creates a new instant of that viewmodel.

It should be possible to delete cart items from Cart page. So if I remove a cart item from Cart page and if I go back to the main page, that change should be visible in the main page too. So maintaining a CartItemsList in the same viewmodel feels like the best approach.

But how to set the same vm instance as both those pages' binding context?

Ruvindra Yohan
  • 67
  • 1
  • 10
  • You can share the same VM instance between two pages, but not with XAML. you’ll have to set it in code – Jason Nov 04 '22 at 11:26
  • @Jason How can I do that exactly? The way I know is creating an object of the viewmodel and assign it to the binding context in Page's constructor. But that again is a new object, not the same instance. – Ruvindra Yohan Nov 04 '22 at 12:10
  • pass the VM instance to the 2nd page on the constructor – Jason Nov 04 '22 at 12:12
  • @Jason I'm using Xamarin.Forms Shell. And I follow MVVM here. Therefore my navigation is happening from the viewmodel, not from the code behind of the page. In that case how can I do that? – Ruvindra Yohan Nov 04 '22 at 12:16
  • @RuvindraYohan Have you solved the problem? – Jianwei Sun - MSFT Nov 25 '22 at 06:22

1 Answers1

0

You can create a static class for ViewModel so that you can call the same VM instance.

Here is the code:

public static class VMInstance
{
    private static SampleViewModel _sampleViewModel = new SampleViewModel();
    public static SampleViewModel SingleVM
    {
        get
        {
            return _sampleViewModel;
        } 
    } 
}

And then Pages.xaml.cs:

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        BindingContext = VMInstance.SingleVM;
    }
}

public partial class CartPage : ContentPage
{
    public CartPage()
    {
        InitializeComponent();
        BindingContext = VMInstance.SingleVM;
    }
}
Jianwei Sun - MSFT
  • 2,289
  • 1
  • 3
  • 7