开发者

How to get Listbox selected index?

开发者 https://www.devze.com 2023-01-29 00:14 出处:网络
I have a Listbox filled with Buttons. When the buttons is clicked then a new Page shows. But i wanna have the selected index of the listbox when i click on the button. But the listboxitem is never sel

I have a Listbox filled with Buttons. When the buttons is clicked then a new Page shows. But i wanna have the selected index of the listbox when i click on the button. But the listboxitem is never selected. Is there a way to get the index where the button lies by clicking the button. Thanks for help.

Example code

 <ListBox>
   <ListBox.ItemTemplate>
        <DataTemplate>
              <Button Click="ViewDetail_Click" Content="{Binding Path=Area}"></Button>
      开发者_开发知识库   </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>


The data context of the button will contain the source data item corresponding to the list item. You've not shown what your ItemsSource is for the list, so I can't show exactly what code you'd need. But something like this:

ObservableCollection<MyDataItem> items = new ObservableCollection<MyDataItem>();
...
myList.ItemsSource = items;
...
private void ViewDetail_Click(object sender, RoutedEventArgs e)
{
    Button b = (Button) sender;
    MyDataItem detailItem = (MyDataItem) b.DataContext;
    int itemIndex = items.IndexOf(detailItem);
}

Of course, if the reason you're asking for the index in the first place is because you want to get hold of the corresponding data item, you don't actually need the index at all - the item's already right there in the data context.

By the way, I wouldn't use a ListBox here. The main thing ListBox brings to the party is selection, but by putting buttons in as the items, you're defeating that - as you've already discovered, the button is handling the mouse input before the list box has a chance to, meaning that you can't actually select the items. At which point, why have a ListBox? A base ItemsControl probably makes more sense. (Wrapped in a ScrollViewer if you need scrolling.)

0

精彩评论

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