在设置辛格尔顿值之前,WPF singelton实例给出空异常

时间:2018-11-27 09:33:20

标签: c# .net wpf

我创建了一个Singelton

static readonly License_plateRequests _instance = new License_plateRequests();

private License_plateRequests()
{
}

public static License_plateRequests instance
{
    get { return _instance; }
}

public License_plate license_plateFirst { get; set; }

我在页面中运行clickevent,以运行一些代码来设置singelton值。这是我在WPF中的第一个应用程序,因此,我不知道这种模式是否正确。

private async void enterButton_Click(object sender, RoutedEventArgs e)
{
    if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Denmark-icon.png")
    {
        nationality = "DK";
    }
    if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Germany-icon.png")
    {
        nationality = "GER";
    }
    if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Norway-icon.png")
    {
        nationality = "NOR";
    }
    if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/Sweden-icon.png")
    {
        nationality = "SWE";
    }
    if (ImageStatus.Source.ToString() == "pack://application:,,,/ParkeringsApp;component/Countries/United-Kingdom-flat-icon.png")
    {
        nationality = "GB";
    }

    var data = await loginRequest.LoginAsync();
    var token = await loginRequest.ParkingToken(data.jwt);
    var licenseplate = await licensePlate.LicensePlate(token, nationality, numberplateInput.Content.ToString());
    var parkings = await licensePlate.getParkingById(token, licenseplate.id);
    try
    {
        foreach (var parking in parkings)
        {
            if (parking == null)
            {
                parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
                NavigationService.Navigate(new RegistredPage());
            }
            else if (parking.time_end == 0)
            {
                NavigationService.Navigate(paymentPage, licenseplate);
                licensePlate.license_plateFirst.country.alpha2 = nationality;
            }
            else
            {
                parkingRequests.ParkCar(token, "aca0cd99-e392-4069-847f-8953ca86d7e6", licenseplate.id);
                NavigationService.Navigate(new RegistredPage());
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine(ex);
    }
}

然后我通过NavigationService导航到下一页PaymentPage。 我在PaymentPage中收到一个nullpointer异常。

public partial class PaymentPage : Page
{
    License_plateRequests licensePlate = License_plateRequests.instance;

    public PaymentPage()
    {
        InitializeComponent();
        System.Diagnostics.Debug.WriteLine(licensePlate.license_plateFirst.country.alpha2);
    }
}

当我尝试运行应用程序时,我得到了空指针。我还没有设置值,所以偏离路线

licensePlate.license_plateFirst.country.alpha2

使我为空。但是我还没有加载该页面,并且我还没有设置值。 我该如何处理,以便在第一次加载页面时可以得到该值?

0 个答案:

没有答案