使用SelectedIndex获取ListBox的项值

时间:2013-05-10 21:44:24

标签: c# windows-phone-7 listbox listboxitem

我的例如ListBox有两个TextBlock,如下所示:

<ListBox Name="listboxNews"
         SelectionChanged="listboxNews_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Width="400"
                        Height="70">
                <TextBlock Text="{Binding Title}" name="title" />
                <TextBlock Text="{Binding Description}" name="desc" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

正如你所看到的,我有listboxNews_SelectionChanged方法,其中我需要选择第一个TextBlock的文本(如果按名称posibble,所以它将按文本块的顺序独立),但是这个,我选择的。例如,如果第一项具有标题“项目1”和第二项“项目2”并且我点击第二项,我需要得到“项目2”。我正在尝试使用listboxNews.Items,但我猜这不正确。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

SelectedItem属性将保存当前选定的对象。您可以转换它并获取Title属性。

试试这段代码:

private void listboxNews_SelectionChanged(object sender, SelectionChangedEventArgs e) {
  var current = listboxNews.SelectedItem as MyObjectType;
  MessageBox.Show(current.Title);
}

使用您的对象类型更改MyObjectType

答案 1 :(得分:0)

这是一个正在运行的Windows Phone 8解决方案的复制和粘贴。

这也在WPF中成功测试过。

    private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
            {
                foreach (UIElement item in (sender as ListBox).Items)
                {
                    if ((sender as ListBox).SelectedItem == item)
                    {
                        foreach (UIElement InnerItem in (item as StackPanel).Children)
                        {
                            if ((InnerItem is TextBlock) && (InnerItem as TextBlock).Name.Equals("title"))
                            {
                                MessageBox.Show((InnerItem as TextBlock).Text);
                            }
                        }
                    }
                }
            }