如何访问我选择的项目?ListBox

3

我希望你能够帮忙翻译以下文本。这段内容与编程有关,涉及到一个名为 MainListBox 的 XAML 页面中的 ListBox。我可以获取所选项目的索引,但如何获取所选项目的数据?

我的 MainListBox_SelectionChanged 代码:

private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        int noteID1 = MainListBox.SelectedIndex+1;

        if (MainListBox.SelectedIndex != null)
        {


            //I can get the index that get selected, 
            Debug.WriteLine(MainListBox.SelectedIndex);



        }

         MainListBox.SelectedIndex = -1;

    }

我的 XAML:

<ListBox x:Name="MainListBox" Margin="6,0,0,0" ItemsSource="{Binding Items}" SelectionChanged="MainListBox_SelectionChanged" Height="578" VerticalAlignment="Bottom" Grid.ColumnSpan="3">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Margin="0,0,0,17" Width="432">
                        <TextBlock x:Name="ItemText" Text="{Binding noteName}" Margin="-2,-13,0,0" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        <TextBlock x:Name="DetailsText" Text="{Binding noteText}" Margin="10,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/>
                        <TextBlock x:Name="noteIdText" Text="{Binding noteID}" Margin="10,-6,0,3" Style="{StaticResource PhoneTextSubtleStyle}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

请有人指导我,谢谢。:)

2
在从MainListBox.SelectedIndex计算出笔记ID后检查其是否为空是毫无意义的。在您的检查执行之前,将抛出NullReferenceException异常。 - Praetorian
5个回答

6

你尝试过使用 MainListBox.SelectedItem 吗?

将 MainListBox.Selecteditem 转换为 [与列表框绑定的类的类型] 类型的数据;


'System.Windows.Controls.ListBox'没有包含名为'SelectedItem'的定义,:(,似乎不起作用啊。有什么想法吗?顺便说一下,谢谢。 - damniatx
啊,谢谢你。我只需要将SelectedItem中的i改成大写。 - damniatx

1
假设您将ListBoxItemsSource属性绑定到Items对象,该对象是类MyDataObject的对象集合。然后,在选择更改回调中使用以下内容:
MyDataObject obj = ( (sender as FrameworkElement).DataContext ) as MyDataObject;
int noteID = obj.noteID;

MyDataObject实际上是什么?如果我没有使用我的数据对象,使用var。使用此方法var data = ((sender as FrameworkElement).DataContext); Debug.WriteLine(data);,输出为wp7_App.MainNotes,看起来方向正确。有什么想法可以获取noteID吗?谢谢。 - damniatx
MyDataObject是包含noteName、noteText和noteID字段的类。在你的情况下,它看起来类名是MainNotes。而且你可以使用var关键字代替类名。 - Praetorian

1

感谢大家的快速回复。

最终我弄清楚了。

 if (MainListBox.SelectedItem != null)
        {


            var data = MainListBox.SelectedItem as Notes;

            NavigationService.Navigate(new Uri("/DetailsPage.xaml?noteID=" + data.noteID, UriKind.Relative));


        }

0
private void MyList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataModel data = (sender as ListBox).SelectedItem as DataModel;
    // data.MyPropertyHere;
}

0

1
此外,我认为你的 MainListBox.SelectedIndex != null 不正确。SelectedIndex 是整数类型,永远不会是 null。 - Howard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接