获取longlistselector中选中项的索引 [英] Get the index of the selected item in longlistselector
问题描述
我有一个很长的列表选择器
I have a long list selector
<phone:LongListSelector x:Name="BTDevices" SelectionChanged="BTDevices_SelectionChanged_1">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" FontSize="30" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
函数定义为:
private void BTDevices_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
//here i want to get the index of the selected item
}
我尝试了以下行
int a = App.ViewModel.Items.IndexOf(sender as ItemViewModel);
但它总是返回-1.
推荐答案
当 SelectionChanged
事件发生时,事件处理程序的 sender
参数表示触发此事件的对象事件.它属于 Object
类型,但您可以将其转换为匹配您的特定控件类型.
When the SelectionChanged
event occurs, the sender
parameter of the event handler represents the object that triggered this event. It is of type Object
, but you can cast it to match your specific control type.
在这种情况下,LongListSelector
:
var myItem = ((LongListSelector) sender).SelectedItem as Model;
(模型代表您的控件处理的数据类型).
(Model represents the type of data your control handles).
之后,在 ItemsSource
中查找该项目并检索其值:
Afterwards, look for that item in the ItemsSource
and retrieve its value :
var myIndex = ((LongListSelector) sender).ItemsSource.IndexOf(myItem);
您已经命名了您的控件,因此您可以使用其名称 BTDevices
而不是 (sender as LongListSelector)
,但我编写的代码行旨在显示sender
对象是什么.
You have named your control, so instead of (sender as LongListSelector)
, you could use its name, BTDevices
, but the code lines I wrote was intended to show you what's what with the sender
object.
或者(这是一种更优雅的方式),如 bland 所示,您可以使用 EventArgs
进行选择:e.AddedItems[0]
Alternatively (and this is a more elegant way), shown by bland, you could use the EventArgs
for selection : e.AddedItems[0]
这篇关于获取longlistselector中选中项的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!