0

Windows 8で現在の場所を取得する簡単なアプリを実行しようとしていますが、awaitキーワードの正しい構文が見つかりません。

エラーは次のようになります。エラー1「await」演算子は非同期メソッド内でのみ使用できます。このメソッドを「async」修飾子でマークし、その戻りタイプを「Task」に変更することを検討してください。

コードは次のとおりです。

public MainPage()
        {
            this.InitializeComponent();

            TextBlock txt = new TextBlock();           
            var location = await InitializeLocationServices();
            txt.Text = location;

            Grid.SetRow(txt, 0);
            Grid.SetColumn(txt, 1);
            //InitializeLocationServices();
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.  The Parameter
        /// property is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private async Task<string> InitializeLocationServices()
        {
            //Initialize geolocator object
            Geolocator geoLocator = new Geolocator();
            if (null != geoLocator)
                try
                {
                    //Try resolve the current location
                    var position = await geoLocator.GetGeopositionAsync();
                    if (null != position)
                    {
                        string city = position.CivicAddress.City;
                        string country = position.CivicAddress.Country;
                        string state = position.CivicAddress.State;
                        string zip = position.CivicAddress.PostalCode;
                        string msg = "I am located in " + country;
                        if (city.Length > 0)
                            msg += ", city of " + city;
                        if (state.Length > 0)
                            msg += ", " + state;
                        if (zip.Length > 0)
                            msg += " near zip code " + zip;
                        return msg;
                    }
                    return string.Empty;
                }
                catch (Exception)
                {
                    //Nothing to do - no GPS signal or some timeout occured.n .
                    return string.Empty;
                }
            return string.Empty;
        }
4

2 に答える 2

3

したがって、コンストラクターで呼び出しているため、機能しません。

私はWin8に精通していませんが、OnNavigatedToの説明から、「///プロパティは通常ページの構成に使用されます。」

初期化の良い候補かもしれません。そこに移動してみましょう:

protected async override void OnNavigatedTo(NavigationEventArgs e)
{

   TextBlock txt = new TextBlock();           
   var location = await InitializeLocationServices();
   txt.Text = location;

   Grid.SetRow(txt, 0);
   Grid.SetColumn(txt, 1);
}
于 2012-06-10T11:52:31.923 に答える
1

関数がを返すことを忘れないでください。Task<string>では、どうしてstring2回戻るのでしょうか。

return string.Empty;

サイドノートに。このチェックが理解できません

Geolocator geoLocator = new Geolocator();
        if (null != geoLocator)
于 2012-06-10T11:21:37.190 に答える