maplemale
maplemale

Reputation: 2036

Xamarin Picker selected item persisting on multiple pages

Question: Perhaps the challenge could be stated this way: How do I bind a single property in a content page to a globally stored variable in Xamarin Forms?

Details: I am using the MVVM pattern. I have a navigation content page (1 of 3 such pages) with a Picker object which is populated dynamically from the collectionModel and said model is read/write. I am attempting to persist the SelectedItem (or index, whichever is most appropriate) thru all 3 content pages such that navigation from page to page shows the same item (from the user's perspective). How should I do this?

I can set the Picker.SelectedIndex manually in ContentPage_Appearing() event. I would much rather use binding.

Upvotes: 0

Views: 901

Answers (1)

Kevin Li
Kevin Li

Reputation: 2258

Follow these steps:

  1. Create a static class, like this:

    public static class DataClass
    {
       public static int PickerSelectedIndex = 0;
    }
    
  2. Add the xmlns:local in ContentPage mark in each Content Page, like this:

    xmlns:local="clr-namespace:DataPersist"
    
  3. Binding the data for your controls in each page's Xaml, like this:

    <Picker  x:Name="picker" SelectedIndex="{x:Static local:DataClass.PickerSelectedIndex}">
    

It works like this:

enter image description here

Upvotes: 1

Related Questions