Issue
I have two pages:
WeatherPage.xaml
Favorites.xaml
I also have a button "Favorite" in WeatherPage.xaml
page.
I want when the user writes something in WeatherPage.xaml
in <Entry/>
field and after pressing the button "Favorite" this text should be displayed on the other page Favorites.xaml
.
Is there an option to keep the transferred text on the page Favorites.xaml
to stay there even when the app is closed ?
I don't have a database and I'm looking for an example of how I can move text from one page to another and save it.
My code in WeatherPage.xaml
is:
<Entry x:Name="_cityEntry"
Grid.Row="1"
Grid.Column="1"
Margin="5,0"
VerticalOptions="Center"
BackgroundColor="Black"
TextColor="White"
Opacity="0.7"
Text="Moscow" />
<ImageButton Source="blackheart.png"
Grid.Row="1"
Grid.Column="3"
WidthRequest="40"
HeightRequest="40"
Opacity="0.7"
Clicked="OnGetFavorites"/>
In my WeatherPage.xaml.cs
I insert this line of code on the button method:
void OnGetFavorites(System.Object sender, System.EventArgs e)
{
Preferences.Set("cityName", _cityEntry.Text);
}
My FavoritePage.xaml.cs
looks like:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
namespace WeatherLocationInfo.Views
{
public partial class Favorites : ContentPage
{
public Favorites()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
FavoriteCities();
}
private void FavoriteCities()
{
string cityName = Preferences.Get("cityName", "default_value");
FavoriteCity.Text = cityName.ToString();
}
}
}
When the application starts on the page, the first entered city is printed from WeatherPage
to Favorites
page, but when it changes the city and clicked the button again the content of the search bar is not updated.
Solution
An easy way to store data even when the app is closed without a database is to store the "_cityEntry text" as application preference. You can directly use the Xamarin.Essentials: Preferences.
create a new preference key-value pair in WeatherPage.xaml.cs
public partial class WeatherPage : ContentPage
{
public WeatherPage()
{
InitializeComponent();
}
private void OnGetFavorites(object sender, EventArgs e)
{
Preferences.Set("cityName", _cityEntry.Text);
Navigation.PushAsync(new FavoritePage());
}
}
get the value of key cityName
in Favorites.xaml.cs
public partial class FavoritePage : ContentPage
{
public FavoritePage()
{
InitializeComponent();
NavigationPage.SetHasNavigationBar(this, false);
FavoriteCities();
}
private void FavoriteCities()
{
string cityName = Preferences.Get("cityName", "default_value");
FavoriteCity.Text = cityName.ToString();
}
}
Besides, if you want to pass the data to an already created page, you can use MVVM and store the city name in the data model.
Answered By - 大陸北方網友
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.