質問

What I'm trying to do is: when a user clicks an item in a listbox, I want to get the item's ID number, which is an attribute. I then want to pass this ID to another page which will display the relevant data.

This is the code I have to attempt to do this:

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));
}

and then on the second page, where I want to display the data, I have the following:

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();
        }
    }

From what I can tell the problem lies on the first page, as the second page is working fine when linked to other pages, where I'm not using listboxes, etc.

Any help is appreciated. Thanks.

EDIT: The code I'm using to populate the listboxes:

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);
            }
        }
    }
役に立ちましたか?

解決

I believe that the issue is with this line:

Pets selectedAnimal = lstCats.SelectedItem as Pets;

The problem, here, is that your ListBox control has items that have Animals as their SelectedItems. What you will want to do is instead bind the ListBox with pets, instead of items:

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


Update

Assuming you want to bind with Animal objects, you can do the following:

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);
        }
    }
}

Then your event handler should look like:

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帰属
所属していません StackOverflow
scroll top