从Windows Phone中的其他类中检索对象

时间:2012-04-17 13:58:53

标签: c# oop windows-phone

目前我在Windows Phone中有一个使用本地数据库的Silverlight应用程序。基本上生成一个listBox来显示存储的'clients'的当前列表,它可以正常工作。现在我想让用户编辑一个客户端的详细信息。为此,我创建了一个新页面,只要用户单击主页面上的按钮,就会加载该页面。该事件如下:

public ClientItem selectedClient;

public void Edit_Click(object sender, EventArgs e)
    {
        if (clientItemsListBox.SelectedItem != null)
        {
            selectedClient = clientItemsListBox.SelectedItem as ClientItem;

            NavigationService.Navigate(new Uri("/EditClient.xaml", UriKind.Relative));
        }
    }

以上只是检查选择了哪个客户端,将其存储为selectedClient并导航到EditClient页面。

在EditClient类中,我有以下方法:

 public void saveButton_Click(object sender, RoutedEventArgs e)
    {
        //Get the client that is selected

        ClientItem clientForDelete = mainPage.selectedClient;
        mainPage.ClientItems.Remove(clientForDelete);
        mainPage.clientDB.ClientItems.DeleteOnSubmit(clientForDelete);

        // Create a new client based on the text boxes
        ClientItem newClient = new ClientItem { ClientName = newClientNameTextBox.Text, ClientSurname = newClientSurnameTextBox.Text, ClientCompany = newClientCompanyTextBox.Text, ClientPhone = int.Parse(newClientPhoneTextBox.Text) };

        // Add new client to the database
        mainPage.clientDB.ClientItems.InsertOnSubmit(newClient);

        // Sava database changes
        mainPage.clientDB.SubmitChanges();

        // Go to main screen
        NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
    }

当我运行此代码时,尝试执行时会收到nullReferenceException:

mainPage.ClientItems.Remove(clientForDelete);

这是因为selectedClient为null。如何在没有null的情况下从另一个类中获取对象?因为我不想从主类中删除该项,以防用户决定取消该操作。此外,我想在页面加载时显示该客户端的详细信息,如果我设法获取对象,我知道该怎么做:)。感谢

1 个答案:

答案 0 :(得分:1)

您可以将客户端作为查询参数传递给其他页面:

   NavigationService.Navigate(
      new Uri("/MainPage.xaml?client="+clientId, UriKind.Relative));

然后在您的MainPage OnNavigatedTo()中检索客户端:

   if (this.NavigationContext.QueryString.ContainsKey("client"))
          client = this.NavigationContext.QueryString["client"];