Issue
I want to save every time strings when button "Favorites" clicked and show on listview on another page.
From my first page I get the string from the button with this code:
void OnGetFavorites(System.Object sender, System.EventArgs e)
{
Preferences.Set("cityName", _cityEntry.Text);
var tabbedPage = this.Parent.Parent as TabbedPage;
tabbedPage.CurrentPage = tabbedPage.Children[2];
}
From my second page I display the strings on the page with this code:
protected override void OnAppearing()
{
base.OnAppearing();
FavoriteCities();
}
private void FavoriteCities()
{
string cityName = Preferences.Get("cityName", "default_value");
var listView = new ListView();
listView.ItemsSource = new[] { cityName };
// Using ItemTapped
listView.ItemTapped += async (sender, e) => {
await DisplayAlert("Tapped", e.Item + " row was tapped", "OK");
Debug.WriteLine("Tapped: " + e.Item);
((ListView)sender).SelectedItem = null; // de-select the row
};
// If using ItemSelected
// listView.ItemSelected += (sender, e) => {
// if (e.SelectedItem == null) return;
// Debug.WriteLine("Selected: " + e.SelectedItem);
// ((ListView)sender).SelectedItem = null; // de-select the row
// };
Padding = new Thickness(0, 20, 0, 0);
Content = listView;
}
void OnItemTapped(System.Object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
}
My ListView looks like:
<ContentPage.Content>
<ScrollView>
<StackLayout Padding="0,30,0,0">
<ListView x:Name="listView"
ItemTapped="OnItemTapped"
ItemsSource="{Binding .}" />
</StackLayout>
</ScrollView>
</ContentPage.Content>
Now every time the old string is replaced with the new one. How can I arrange all the strings?
Solution
there are a lot of different ways to approach this. I'm going to give you a fairly simple one
first, you need a data structure to hold your data
ObservableCollection<string> CityData { get; set; }
then you need to update your XAML to bind to it
... ItemsSource="{Binding CityData}" />
then in the page constructor initialize CityData
and set the BindingContext
CityData = new ObservableCollection<string>();
this.BindingContext = this;
important get rid of FavoriteCities
there is nothing useful in there, and for some reason you are completely recreating the UI code that you already have in your XAML
then add a public method to your page to update the data
public void AddCity(string city)
{
CityData.Add(city);
}
finally, in your other page
void OnGetFavorites(System.Object sender, System.EventArgs e)
{
// I really don't know what this is for
Preferences.Set("cityName", _cityEntry.Text);
var tabbedPage = this.Parent.Parent as TabbedPage;
// important - cast to the correct type of Page2 - I don't know what that is
var page = (MyPageClass) tabbedPage.Children[2];
// add the new City
page.AddCity(cityEntry.Text);
// navigate
tabbedPage.CurrentPage = page;
}
Answered By - Jason
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.