得到longlistselector所选项目的索引 [英] Get the index of the selected item in longlistselector

查看:150
本文介绍了得到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>



该函数定义为:

The function is defined as:

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。

But it always returns -1.

推荐答案

的SelectionChanged 事件发生时,发件人事件处理程序的参数代表触发此事件的对象。它的类型是对象的,但你可以将它转换为满足您的特定控件类型。

When the SelectionChanged event occurs, the senderparameter 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);

您已经命名自己的控制,所以不是(发件人为LongListSelector),你可以使用其名称, BTDevices ,但我写的代码行是为了告诉你什么是与发送什么对象。

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.

另外(这是一个更优雅的方式),由平淡所示,你可以使用的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆