簡體   English   中英

獲取SelectedItems的屬性並將其傳遞到WP8中的新頁面

[英]Get a SelectedItems's attribute and pass it to a new page in WP8

我想做的是:當用戶單擊列表框中的項目時,我想獲取該項目的ID號,這是一個屬性。 然后,我想將此ID傳遞到另一個頁面,該頁面將顯示相關數據。

這是我必須嘗試執行的代碼:

private void lstCats_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
        Pets selectedAnimal = lstCats.SelectedItem as Pets;
        NavigationService.Navigate(new Uri("/ViewPet.xaml?msg=" + selectedAnimal.ID, UriKind.Relative));
}

然后在第二頁上要顯示數據的位置,我具有以下內容:

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);

        string msg = "";

        if (NavigationContext.QueryString.TryGetValue("msg", out msg))
        {
            id = Convert.ToInt16(msg);

            DisplayDetails();
            DisplayImage();
        }
    }

據我所知,問題出在第一頁上,因為第二頁在鏈接到其他頁面,不使用列表框等時工作正常。

任何幫助表示贊賞。 謝謝。

編輯:我用來填充列表框的代碼:

private void DisplayCats()
    {
        foreach (Pets temp in thisApp.pets)
        {
            if (temp.Category.Contains("Cat"))
            {
                Animal animal = new Animal() { Details = temp.Name + "\n" + temp.Category + " / " + temp.Subcategory + "\n€" + temp.Price.ToString(), ImageURI = temp.Image };
                lstCats.Items.Add(animal);
            }
        }
    }

我認為問題出在這一行:

Pets selectedAnimal = lstCats.SelectedItem as Pets;

這里的問題是您的ListBox控件具有將Animal作為其SelectedItem的項目。 您要做的是將ListBox與寵物而不是物品綁定在一起:

private void DisplayCats()
{
    foreach (Pets temp in thisApp.pets)
    {
        if (temp.Category.Contains("Cat"))
        {
            lstCats.Items.Add(temp);
        }
    }
}


更新資料

假設要與Animal對象綁定,可以執行以下操作:

private void DisplayCats()
{
    foreach (Pets temp in thisApp.pets)
    {
        if (temp.Category.Contains("Cat"))
        {
            //note that I added the ID property --v
            Animal animal = new Animal() { ID = temp.ID, Details = temp.Name + "\n" + temp.Category + " / " + temp.Subcategory + "\n€" + temp.Price.ToString(), ImageURI = temp.Image };
            lstCats.Items.Add(animal);
        }
    }
}

然后,您的事件處理程序應如下所示:

private void lstCats_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Animal selectedAnimal = lstCats.SelectedItem as Animal;
    NavigationService.Navigate(new Uri("/ViewPet.xaml?msg=" + selectedAnimal.ID, UriKind.Relative));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM