Windows phone 7 列表框SelectedIndex始终为-1

Windows phone 7 列表框SelectedIndex始终为-1,windows-phone-7,listbox,selectedindex,Windows Phone 7,Listbox,Selectedindex,我有一个列表框,其中按钮和文本块作为ItemTemplate。按钮有一个onClick事件 我只想获得单击项目的索引,但我的列表框中的SelectedIndex属性始终为-1 如何获取已单击项的索引?您可能需要在列表框中实际选择某个内容,然后:p如果要获取与当前列表项关联的数据对象,请使用RouteCommand。下面是一个例子 <ListView.ItemTemplate> <DataTemplate> <Button Margin="5,0" Com

我有一个列表框,其中按钮和文本块作为ItemTemplate。按钮有一个
onClick
事件

我只想获得单击项目的索引,但我的列表框中的
SelectedIndex
属性始终为-1


如何获取已单击项的索引?

您可能需要在列表框中实际选择某个内容,然后:p

如果要获取与当前列表项关联的数据对象,请使用RouteCommand。下面是一个例子

<ListView.ItemTemplate>
  <DataTemplate>
    <Button Margin="5,0" Command="{StaticResource ButtonCommand}" 
                         CommandParameter="{Binding}">
  </DataTemplate>
<ListView.ItemTemplate>

您可以提前使用任何MVVM框架,在模型中定义所有命令和命令逻辑,然后只将这些命令绑定到相应的元素。

问题在于按钮控件正在吞咽鼠标事件以提供单击行为,因此列表框从未收到任何事件来告诉它选择已更改

正如@Alexander所建议的,您可以使用MVVM风格的方法和命令来处理视图模型中的操作,并将数据上下文作为参数传递


或者,您可以将按钮替换为任何其他布局控件,并使用来自的手势服务或使用常规的
MouseLeftButtonUp
事件。在任何一种情况下,鼠标事件都会弹出,并使列表框能够处理选择。

非常感谢!我只需删除按钮,然后创建SelectionChanged事件(使用相同的代码)我是C#and development中的一个新成员,所以这是最适合我的方式)
<RoutedCommand x:Key="ButtonCommand"/>
<ListView.CommandBindings>
  <CommandBinding Command="{StaticResource ButtonCommand}" Executed="Button_Click"/>
</ListView.CommandBindings>
    Button_Click(object sender, ExecutedRoutedEventArgs e)
    {
        e.Parameter// object that you Specified in CommandParameter
    }