1

我有一个带有两个 HamburgerMenuButtons 的应用程序:TYMLY 和 NEWTYMLY。TYMLY 是主页。我正在使用 Template10 MVVM。在启动时它根据需要导航到 TYMLY 页面,我点击 NEWTYMLY 页面并继续执行一些任务以创建一个要添加到 TYMLY 主页中的 Griview 的对象。在 PageHeader 部分中,我有一个按钮,用于保存此对象并继续导航到 TYMLY 主页并将对象添加到 Gridview。每当我按下此按钮时,我都会在以下行收到 System.NullException:

public void SaveNewTymly() =>
        NavigationService.Navigate(typeof(Views.MainPage), New_Tymly);

我还注意到,如果我按下模板附带的其他按钮(如设置、隐私和关于我们),也会发生 System.NullException;

public void GotoSettings() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 0);

    public void GotoPrivacy() =>
        NavigationService.Navigate(typeof(SettingsPage), 1);

    public void GotoAbout() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 2);

我想知道在这种情况下如何处理导航。谢谢你。 MainPage NewPage 创建对象以添加到主页中的gridview

新TymlyModel.cs

using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Tymly_Revamped.Models;
using Tymly_Revamped.Views;
using Windows.UI.Xaml.Navigation;

namespace Tymly_Revamped.ViewModels
{
    class NewTymlyViewModel : ViewModelBase
    {
        private Tymly newTymly;
        public Tymly New_Tymly { get { return newTymly; } set { Set(ref newTymly, value); } }


    bool trafficFlow;





    public NewTymlyViewModel()
    {
      newTymly = new Tymly();
    }

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> suspensionState)
    {
        New_Tymly = (suspensionState.ContainsKey(nameof(New_Tymly))) ? suspensionState[nameof(New_Tymly)] as Tymly : parameter as Tymly;
        await Task.CompletedTask;
    }

    public override async Task OnNavigatedFromAsync(IDictionary<string, object> suspensionState, bool suspending)
    {
        if (suspending)
        {


            suspensionState[nameof(New_Tymly)] = New_Tymly;
        }
        await Task.CompletedTask;
    }

  public bool TrafficFlow
    {
        get { return trafficFlow; Debug.WriteLine(trafficFlow); }
        set { trafficFlow = !trafficFlow; }

    }

    public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
    {
        args.Cancel = false;
        await Task.CompletedTask;
    }

    public void SaveNewTymly() =>
        NavigationService.Navigate(typeof(Views.MainPage), New_Tymly);


    public void GotoSettings() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 0);

    public void GotoPrivacy() =>
        NavigationService.Navigate(typeof(SettingsPage), 1);

    public void GotoAbout() =>
        NavigationService.Navigate(typeof(Views.SettingsPage), 2);
}

}

using NodaTime.TimeZones;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Maps;
using Tymly_Revamped.Models;
using Tymly_Revamped.ViewModels;
using Tymly_Revamped.Views;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Markup;
using System.Collections.ObjectModel;
using Windows.ApplicationModel.Contacts;
using System.IO;
using System.Diagnostics;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;
namespace Tymly_Revamped.Views
{

    public sealed partial class NewTymly : Page
    {


    private uint desiredAccuracy_meters = 0;
    private CancellationTokenSource cancelTokenSrc = null;

    private IEnumerable<string> zonalIds;

    IReadOnlyList<GetContactDetails> condetails;
    public IReadOnlyList<GetContactDetails> ConDetails { get { return condetails; } set { condetails = value; } }
    ObservableCollection<GetContactDetails> contacts;
    public ObservableCollection<GetContactDetails> Contacts { get { return contacts; } set { contacts = value; } }

    public NewTymly()
    {
        this.InitializeComponent();
        NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
        DataContext = new NewTymlyViewModel();
        searchLocation.Loaded += Map_Loaded;
        searchLocation.MapTapped += Map_Tapped;
        searchLocation.MapDoubleTapped += Map_DoubledTapped;
        searchLocation.Style = MapStyle.Road;
    }

    private void Map_DoubledTapped(MapControl sender, MapInputEventArgs args)
    {
        throw new NotImplementedException();
    }

    private void Map_Tapped(MapControl sender, MapInputEventArgs args)
    {
        var tappedPositon = args.Location.Position;
         if (sender.ZoomLevel < 20)
        {
            sender.ZoomLevel += 2;
        }
        else if (sender.ZoomLevel >= 20)
        {
            sender.ZoomLevel = 12;
        }
    }

    private async void Map_Loaded(object sender, RoutedEventArgs e)
    {            
        try
        {
            var requestLocationAccess = await Geolocator.RequestAccessAsync();
            switch (requestLocationAccess)
            {
                case GeolocationAccessStatus.Allowed:
                    cancelTokenSrc = new CancellationTokenSource();
                    CancellationToken token = cancelTokenSrc.Token;


                    Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = desiredAccuracy_meters };
                    Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);

                    searchLocation.Center =
                        new Geopoint(new BasicGeoposition()
                        {
                            Latitude = pos.Coordinate.Point.Position.Latitude,
                            Longitude = pos.Coordinate.Point.Position.Longitude
                        });
                    searchLocation.ZoomLevel = 1;                        
                    break;
            }
        }
        catch (TaskCanceledException)
        {
            throw new TaskCanceledException();
        }
        finally
        {
            cancelTokenSrc = null;
        }
    }

    private async void ShowOnMap(double lati, double longi)
    {
        try
        {
            var accessLocation = await Geolocator.RequestAccessAsync();

            switch (accessLocation)
            {

                case GeolocationAccessStatus.Allowed:
                    cancelTokenSrc = new CancellationTokenSource();
                    CancellationToken token = cancelTokenSrc.Token;


                    Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = desiredAccuracy_meters };
                    Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);

                    searchLocation.Center =
                        new Geopoint(new BasicGeoposition()
                        {
                            Latitude = lati,
                            Longitude = longi,
                        });
                    searchLocation.ZoomLevel = 5;
                    break;

            }
        }
        catch (TaskCanceledException)
        {

        }
        finally
        {
            cancelTokenSrc = null;
        }
    }

    private void styleCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        switch (mapStyle.SelectedIndex)
        {
            case 0:
                searchLocation.Style = MapStyle.None;
                break;
            case 1:
                searchLocation.Style = MapStyle.Road;
                break;
            case 2:
                searchLocation.Style = MapStyle.Aerial;
                break;
            case 3:
                searchLocation.Style = MapStyle.AerialWithRoads;
                break;
            case 4:
                searchLocation.Style = MapStyle.Terrain;
                break;
        }
    }

    public void InputLocation_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
    {
        if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
        {
            zonalIds = TzdbDateTimeZoneSource.Default.ZoneLocations.
                Where(loc => loc.CountryName.IndexOf(sender.Text, StringComparison.CurrentCultureIgnoreCase) > -1).
                Select(loc => loc.ZoneId);
            sender.ItemsSource = zonalIds.ToList();
        }
    }

    public void InputLocation_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
    {
        MapGlyphs mapGlyph = new MapGlyphs();
        if (args.ChosenSuggestion != null)
        {
            var selectedZonalId = args.ChosenSuggestion as string;

            string state = selectedZonalId.Remove(0, selectedZonalId.IndexOf("/") + 1).Replace("_", " ");

            var country = TzdbDateTimeZoneSource.Default.ZoneLocations.
            Where(zoneloc => zoneloc.ZoneId == selectedZonalId).Select(zoneloc => zoneloc.CountryName).
            ElementAtOrDefault(0);

            var timeZone = TzdbDateTimeZoneSource.Default.ZoneLocations.
                Where(tym => tym.ZoneId == selectedZonalId).Select(tymZone => TzdbDateTimeZoneSource.Default.WindowsMapping.
                MapZones.FirstOrDefault(tym => tym.TzdbIds.Contains(selectedZonalId))).
                Where(tym => tym != null).Select(tym => tym.WindowsId).Distinct();

            var lattitude = TzdbDateTimeZoneSource.Default.ZoneLocations.
                Where(lat => lat.ZoneId == selectedZonalId).Select(tym => tym.Latitude);

            var longitude = TzdbDateTimeZoneSource.Default.ZoneLocations.
                Where(lon => lon.ZoneId == selectedZonalId).Select(tym => tym.Longitude);

            if (timeZone.Count() != 0)
            {
                var dateTime = TimeZoneInfo.ConvertTime(
                    DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(timeZone.ElementAt(0)));
                if (mapGlyph.PlaceIcon.ContainsKey(state))
                {
                    locationText.Text = state;
                    ViewModel.New_Tymly.Location = state;
                    ViewModel.New_Tymly.MapIcon = mapGlyph.MapLocationIcon(state);
                }
                else
                {
                    locationText.Text = country;
                    ViewModel.New_Tymly.Location = country;
                    ViewModel.New_Tymly.MapIcon = mapGlyph.MapLocationIcon(country);
                }

                dateText.Text = dateTime.ToString("D");
                timeText.Text = dateTime.ToString("T");
                ViewModel.New_Tymly.Datetime = dateTime;
                IconPath.Data = PathMarkupToGeometry(ViewModel.New_Tymly.MapIcon);
            }
            else
            {

            }
            ShowOnMap(lattitude.ElementAt(0), longitude.ElementAt(0));
        }
    }

    public void InputLocation_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
    {
        MapGlyphs mapGlyph = new MapGlyphs();
        var place = args.SelectedItem as string;
        string state = place.Remove(0, place.IndexOf("/") + 1).Replace("_", " ");

        var country = TzdbDateTimeZoneSource.Default.ZoneLocations.
        Where(zoneloc => zoneloc.ZoneId == place).Select(zoneloc => zoneloc.CountryName).
        ElementAtOrDefault(0);
        var timeZone = TzdbDateTimeZoneSource.Default.ZoneLocations.
                Where(x => x.ZoneId == place).Select(tz => TzdbDateTimeZoneSource.Default.WindowsMapping.
                MapZones.FirstOrDefault(x => x.TzdbIds.Contains(place))).
                Where(x => x != null).Select(x => x.WindowsId).Distinct();
        var latitude = TzdbDateTimeZoneSource.Default.ZoneLocations.
            Where(x => x.ZoneId == place).Select(tz => tz.Latitude);
        var longitude = TzdbDateTimeZoneSource.Default.ZoneLocations.
            Where(x => x.ZoneId == place).Select(tz => tz.Longitude);

        if (timeZone.Count() != 0)
        {
            var dateTime = TimeZoneInfo.ConvertTime(
                DateTime.Now, TimeZoneInfo.FindSystemTimeZoneById(timeZone.ElementAt(0)));
            if (mapGlyph.PlaceIcon.ContainsKey(state))
            {
                locationText.Text = state;
                ViewModel.New_Tymly.Location = state;
                ViewModel.New_Tymly.MapIcon = mapGlyph.MapLocationIcon(state);
            }
            else
            {
                locationText.Text = country;
                ViewModel.New_Tymly.Location = country;
                ViewModel.New_Tymly.MapIcon = mapGlyph.MapLocationIcon(country);
            }

            dateText.Text = dateTime.ToString("D");
            timeText.Text = dateTime.ToString("T");
            ViewModel.New_Tymly.Datetime = dateTime;
            IconPath.Data = PathMarkupToGeometry(ViewModel.New_Tymly.MapIcon);
        }
        else
        {

        }

        ShowOnMap(latitude.ElementAt(0), longitude.ElementAt(0));
    }

    Geometry PathMarkupToGeometry(string pathMarkup)
    {
        string xaml =
        "<Path " +
        "xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>" +
        "<Path.Data>" + pathMarkup + "</Path.Data></Path>";
        var path = XamlReader.Load(xaml) as Windows.UI.Xaml.Shapes.Path;
        // Detach the PathGeometry from the Path
        Geometry geometry = path.Data;
        path.Data = null;
        return geometry;
    }

    private async void AddContacts(object sender, RoutedEventArgs e)
    {            
        var contactPicker = new ContactPicker();
        contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.Email);
        contactPicker.DesiredFieldsWithContactFieldType.Add(ContactFieldType.PhoneNumber);

        var selectedContacts = await contactPicker.PickContactsAsync();
        ContactStore contactStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);


        if (selectedContacts != null && selectedContacts.Count > 0)
        {
            foreach (var item in selectedContacts)
            {
                Contact realContact = await contactStore.GetContactAsync(item.Id);

                ViewModel.New_Tymly.ContactList.Add(new ContactItemAdapter(realContact));
                var t = new ContactItemAdapter(realContact).Thumbnail;
                Debug.WriteLine(t);

            }
        }

    }

    private void DeleteContact(object sender, RoutedEventArgs e)
    {
        ContactItemAdapter item = (ContactItemAdapter)(sender as Button).DataContext;
        Debug.WriteLine(item.Name);
        if (addContacts.Items.Contains(item))
        {
            ViewModel.New_Tymly.ContactList.Remove(item);
        }
    }


}

}

4

0 回答 0