Get items values of ListBox with SelectedIndex

2019-08-24 03:51发布

问题:

I've got for example ListBox with two TextBlocks like this:

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

And as you can see, I've got listboxNews_SelectionChanged method, in which i need to select Text of first TextBlock (if posibble by name so it will be independent on order of textblocks), but this one, which I select. For example if first item has title "Item 1" and second "Item 2" and I click on second one, i need to get "Item 2". I was trying something with listboxNews.Items, but i guess this is not correct. Thanks for help.

回答1:

The SelectedItem property will hold the currently selected object. You can just cast that and take the Title property.

Try this code:

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

Change MyObjectType with the type of your object.



回答2:

This is a copy and paste out of a working Windows Phone 8 solution.

This was also tested successfully in 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);
                            }
                        }
                    }
                }
            }