【问题标题】:How to get text on entry from another page Android - Xamarin如何从另一个页面获取文本输入 Android - Xamarin
【发布时间】:2021-05-21 06:09:31
【问题描述】:

我想从另一个页面获取<Entry/> 上的字符串。在我的 iOS 项目中有效,但在我的 Android 项目中,仅当我单击第一页后单击第二页时才有效,第二次单击第二页时,他从 OnApearing() 方法工作。我希望第一次单击以从另一个页面显示字符串。

我在第二页的代码是:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace WeatherLocationInfo.Views
{
    public partial class AboutPage : ContentPage
    {
        RestServiceForecast _restServiceForecast;

    public AboutPage()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        _restServiceForecast = new RestServiceForecast();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        string cityName = Preferences.Get("cityName", "default_value");

        _cityEntry.Text = cityName;

        _ = WeatherForecast();
    }

当我将此代码放在构造函数中时,他不在 android 上工作。 (在 iOS 中我没有问题)。

string cityName = Preferences.Get("cityName", "default_value");

    _cityEntry.Text = cityName;

    _ = WeatherForecast();

从第一页我得到这个代码的字符串:

Preferences.Set("cityName", _cityEntry.Text);

【问题讨论】:

  • 为什么要使用首选项在页面之间传递数据?使用构造函数或公共属性或方法会更直接。这已在之前的问题中向您展示过。
  • 你能举个例子吗?

标签: c# android xamarin


【解决方案1】:

通过构造函数传递值

在您的About 页面中

private string city;

public AboutPage(string city)
{
    InitializeComponent();

    NavigationPage.SetHasNavigationBar(this, false);

    _restServiceForecast = new RestServiceForecast();

    this.city = city;
}

然后当你从第一页调用它时

Navigation.PushAsync(new AboutPage(_cityEntry.Text));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    相关资源
    最近更新 更多