MCKool
MCKool

Reputation: 23

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?

Upvotes: 2

Views: 790

Answers (3)

Derek Lakin
Derek Lakin

Reputation: 16319

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.

Upvotes: 2

Alexander
Alexander

Reputation: 1297

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.

Upvotes: 0

Claus J&#248;rgensen
Claus J&#248;rgensen

Reputation: 26344

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

Upvotes: 0

Related Questions