Get items values of ListBox with SelectedIndex

依然范特西╮ 提交于 2019-12-12 03:52:52

问题


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);
                            }
                        }
                    }
                }
            }


来源:https://stackoverflow.com/questions/16491236/get-items-values-of-listbox-with-selectedindex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!