开发者

ListBox SelectedIndex is always -1

I have a Listbox with Button and Textblock as ItemTemplate. Button has an onClick event.

All i want is to get the index of the clicked item, but SelectedIndex property in my ListBox 开发者_高级运维is always -1!

How can I get the index of the clicked item?


The problem is that the Button control is swallowing the mouse events to provide the Click behavior, so the ListBox never receives any events to tell it that the selection has changed.

As @Alexander suggests, you could use an MVVM-style approach with commands to handle the action in a view model and pass the data context as the parameter.

Alternatively, you could replace the Button with any other layout control and either use the gesture service from the Silverlight Toolkit or use the regular MouseLeftButtonUp event. In either instance, the mouse events will bubble up and enable the ListBox to handle selection.


You might want to actually select something in your listbox then :p


If you want to get data object associated with current ListItem use RouteCommand. Here is example

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

You need also define Command at least in ListView.Resources

<RoutedCommand x:Key="ButtonCommand"/>

And then setup CommandBinding like this

<ListView.CommandBindings>
  <CommandBinding Command="{StaticResource ButtonCommand}" Executed="Button_Click"/>
</ListView.CommandBindings>

In the end write handler

    Button_Click(object sender, ExecutedRoutedEventArgs e)
    {
        e.Parameter// object that you Specified in CommandParameter
    }

In advance you can use any MVVM framework, define all command and commands logic in model and then just bind this commands to corresponding elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜