使用SelectedIndex获取ListBox的项目值

使用SelectedIndex获取ListBox的项目值

本文介绍了使用SelectedIndex获取ListBox的项目值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有两个这样的TextBlock ListBox:

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>

正如您所看到的,我有listboxNews_SelectionChanged方法,在该方法中,我需要选择第一个TextBlock的Text(如果按名称定位,则它将独立于文本块的顺序),但是我需要选择选择.例如,如果第一个项目的标题为项目1",第二个项目的标题为项目2",而我单击第二个项目,则需要获取项目2".我正在尝试使用listboxNews.Items进行操作,但是我猜这是不正确的.感谢您的帮助.

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.

推荐答案

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

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

尝试以下代码:

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

用对象的类型更改MyObjectType.

这篇关于使用SelectedIndex获取ListBox的项目值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 08:06