问题
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:
Create a static class, like this:
public static class DataClass { public static int PickerSelectedIndex = 0; }
Add the
xmlns:local
inContentPage
mark in each Content Page, like this:xmlns:local="clr-namespace:DataPersist"
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