繁体   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