如果我在不使用MessageDialog加载页面时隐藏一些控件,应用程序崩溃

时间:2015-07-04 14:41:35

标签: c# xaml windows-phone-8.1

我有一个应用程序,其中我有一个设置,允许用户停止应用程序访问其位置。它存储在Windows.Storage.ApplicationData.Current.RoamingSettings.Values [" location"]中。如果位置服务+此设置允许访问,则我加载打开地图的页面。如果该设置允许访问且位置服务为关闭,则会显示一条消息,并在页面加载时隐藏一些控件。如果设置已关闭,那么我只想隐藏控件而不显示任何消息。

protected  override void OnNavigatedTo(NavigationEventArgs e)
    {

         .....
        // MUST ENABLE THE LOCATION CAPABILITY!!!
          var locator = new Geolocator();
          locator.DesiredAccuracyInMeters = 50;
          locator.ReportInterval = (uint)TimeSpan.FromSeconds(15).TotalMilliseconds;
          setloc(locator);
          this.navigationHelper.OnNavigatedTo(e);

    }

    public async void setloc(Geolocator locator)
    {
        if (locator.LocationStatus != PositionStatus.Disabled && (bool)Windows.Storage.ApplicationData.Current.RoamingSettings.Values["location"]==true)
        {
            var position = await locator.GetGeopositionAsync();
            await MyMap.TrySetViewAsync(position.Coordinate.Point, 16D);
            ....
            return;
        }
        else if (locator.LocationStatus == PositionStatus.Disabled && (bool)Windows.Storage.ApplicationData.Current.RoamingSettings.Values["location"] == true)
        {

            MessageDialog msgbox = new MessageDialog("Location Services are turned off. Please turn them on to save Location while saving a Tip", "Location Unavailable");
            await msgbox.ShowAsync();
            savebutton.Visibility = Visibility.Collapsed;
            myMapBlock.Visibility = Visibility.Collapsed;
            return;

        }
       ***// MessageDialog msgbox1 = new MessageDialog("Location Services are turned off. Please turn them on to save Location while saving a Tip", "Location Unavailable");
       // await msgbox1.ShowAsync();***

       savebutton.Visibility = Visibility.Collapsed;
       myMapBlock.Visibility = Visibility.Collapsed;

    }

当设置开启时(true),一切都很好但是当它关​​闭(假)时,会发生奇怪的事情。 上面的代码不起作用。它会导致应用程序崩溃,但是当我取消注释代码中***内的部分时,将显示该消息并正确加载页面。如果我只是尝试隐藏myMapBlock和保存按钮而不使用MessageDialog,它会崩溃。 我想隐藏控件而不使用MessageDialog。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以更改以下行:

setloc(locator);

为:

await Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { await setloc(locator); });

(将void setloc方法的签名更改为Task)

在我看来,页面尚未加载,MessageDialog无法显示。 Dispatcher.RunAsync应将此操作排入队列,并应在正确的页面初始化后进行处理。

也应该在你的location-messagedialog代码之前进行基础.OnNavigatedTo(..)调用。

我的猜测 - 你能提供一个崩溃堆栈跟踪吗?