检查参数是否已在 windows 通用 c# 代码中传递

Checking if parameter has been passed in windows universal c# code

我正在传递参数以允许用户返回并进行更改

 private void go_back_btn_Click(object sender, RoutedEventArgs e)
    { 

         Frame.Navigate(typeof(TruckRegistrationPage), this.truckdetails);  
    }

卡车注册页面现已上线

        protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        this.changeddetails= (TruckRegistrationDetails)e.Parameter;
        //set the form fields based on the details
        if (e.Parameter) //this throws an error of boolean not casted
        {
            truck_reg_no.Text = changeddetails.reg_no;
            transporter_name.Text = truckdetails.owner_id;

             .......assign other xaml controls

        }

    } 

我传递的参数是 TruckRegistrationDetails 类型,它是一个 class 包含如下属性

    class TruckRegistrationDetails
    {
      public int id { get; set; }
      public string reg_no { get; set; }
       public int truck_category { get; set; }

        .......others
    }

我如何检查是否已传递任何参数并因此分配 xaml 控件值

将您的代码更改为此

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        changeddetails = (TruckRegistrationDetails)e.Parameter;

        if (changeddetails != null) 
        {
            truck_reg_no.Text = changeddetails.reg_no;
            //do what ever you want ^^
        }
    }

您的检查是针对布尔值,但 e.Parameter 是对象。这是 link 到 MSDN https://msdn.microsoft.com/de-de/library/windows/apps/windows.ui.xaml.navigation.navigationeventargs.parameter.aspx

我在使用这种方法时遇到错误,因为在某些时候 OnNavigatedTo 是用空字符串的 NavigationEventArgs.Parameter 调用的。当对象被强制转换为我传递的对象类型时,这会导致 Cast 异常。 我用过:

        if (args.Parameter is DeviceInformation)
        {
            DeviceInformation deviceInfo = (DeviceInformation)args.Parameter;
            //Do something with object
        }

这里先检查对象的类型,看它是否符合预期,然后转换不会抛出异常。