Skip to main content
 首页 » 编程设计

c#之如何在 Windows Phone 7.1 的列表框中选择一个项目

2024年02月20日13linjiqin

我是初学者,正在为 Windows Phone 7.1 创建一个应用程序,我正在尝试通过列表框中的单击事件导航到新页面,基本上我希望列表框中的每个项目都应导航到不同的页面我尝试了以下代码

private void FirstListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
     { 
        // If selected index is -1 (no selection) do nothing 
        if (FirstListBox.SelectedIndex == -1) 
            return; 
 
        // Navigate to the new page 
        NavigationService.Navigate(new Uri("/FirstItemPage1.xaml?selectedItem=" + FirstListBox.SelectedIndex, UriKind.Relative)); 
 
        // Reset selected index to -1 (no selection) 
        FirstListBox.SelectedIndex = -1; 
    } 

上面的代码运行良好,但问题是它将整个列表框带到同一页面,但我希望每个单独的项目都导航到不同的页面

请您参考如下方法:

您可以在将项目添加到列表框时为列表框中的每个项目设置 SelectedValue。

假设您通过代码将字符串列表分配给 ListBox 的 ItemsSource(或者它可能通过数据绑定(bind)发生)。您可以在页面的构造函数中添加项目。

var items = new List<string>(){ "Home", "Details" }; 
FirstListBox.ItemsSource = items; 

在 SelectionChanged 事件中添加一个 switch 语句,它根据所选项目的 SelectedValue 导航到不同的页面,如下所示:

private void FirstListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e) 
 { 
    // If selected index is -1 (no selection) do nothing 
    if (FirstListBox.SelectedIndex == -1) 
        return; 
 
    switch (FirstListBox.SelectedValue) 
        { 
            case "Home":// Navigate to the page 
    NavigationService.Navigate(new Uri("/Home.xaml", UriKind.Relative)); break; 
            case "Details":// Navigate to the page 
    NavigationService.Navigate(new Uri("/Details.xaml", UriKind.Relative)); break;default:break; 
        } 
 
 
    // Reset selected index to -1 (no selection) 
    FirstListBox.SelectedIndex = -1; 
} 

如果您将复杂对象绑定(bind)到 ListBox,您可以使用 ListBox 的 SelectedItem-Property,因为该属性包含已绑定(bind)到该 ListBoxItem 的对象,并根据复杂的属性之一区分情况对象,例如名称或 ID。