Xamarin Picker selected item persisting on multiple pages

谁都会走 提交于 2020-08-06 06:20:12

问题


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.


回答1:


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:



来源:https://stackoverflow.com/questions/47007802/xamarin-picker-selected-item-persisting-on-multiple-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!