为什么此显示警报不起作用?当我在按钮Clicked事件中尝试时,它工作正常,但在功能中却无法工作

时间:2019-08-11 09:12:23

标签: c# xamarin.forms

1)它是天气Api,并且我希望在没有互联网连接到设备时不显示互联网连接。

        public async void method()
    {
        Indicator.IsRunning = true;
        Weather weather = await GetWeather(nameplace.Text);

        if (weather != null)
        {
            if (weather.message == "city not found")
            {
                 txtLocation.Text = "city not found";
            }
            else
            {
                Location.Text = weather.Title;
                Temperature.Text = weather.Temperature;
                Temperature.Text += "°";
                txtWind.Text = weather.Wind;
                Humidity.Text = weather.Humidity;
                Sunrise.Text = weather.Sunrise;
                Sunset.Text = weather.Sunset;
                double condition = Convert.ToDouble(weather.Condition);
                if (condition >= 0 && condition < 30)
                {
                    Condition.Text = "Clear Sky";
                }
                else if (condition >= 30)
                {
                    Condition.Text = "Cloudy";
                }
            }

        }
        else
        {
       await DisplayAlert("Alert", "Sorry ! No internet connection","Ok")`
        }
    }

3)//下面我拥有的getservice函数中

if (Plugin.Connectivity.CrossConnectivity.Current.IsConnected)
        {
            var response = await client.GetAsync(QueryString);

// pQueryString是http请求

            _httpStatusCode = response.StatusCode.ToString();
            if (response == null)
            {
                return "Sorry! No record Found.";
            }
            else if (response != null)
            {
                string json = response.Content.ReadAsStringAsync().Result;
                data = JsonConvert.DeserializeObject(json);

            }
        }
        else
        {
            data = null;
        }
        return data;

4)我返回了null并在其中放置了一个条件,以便它可以显示警告说没有互联网连接

1 个答案:

答案 0 :(得分:0)

您的异步void方法可能会与Thread上下文混淆,最终您可能不会在ui线程中调用代码。

您可以尝试以下方法:

Xamarin.Forms.Device.BeginInvokeOnMainThread(
    () => DisplayAlert("Alert", "Sorry ! No internet connection","Ok"));

此外,将UI代码放入服务层也是一种糟糕的设计。 您应该在DisplayAlert中而不是在服务中调用ViewModel代码。