How to implement Hold in Listbox?

If I have a list, I want to get the index of the list.

This is my code:

<ListBox Margin="0,0,-12,0" Hold="holdlistbox" x:Name="listbox" SelectionChanged="listbox_SelectionChanged" SelectedIndex="-1"> </ListBox> private void holdlistbox(object sender, System.Windows.Input.GestureEventArgs e) { //How to get ListBox index here } 

If anyone knows, help me do this.

+4
source share
2 answers

e.OriginalSource you will receive the actual control that was held (the topmost control right under your finger). Depending on your ItemTemplate and where you are holding it, this could be any control in the element. Then you can check the DataContext of this control to get an object attached to this element (in your comment, it will be an ItemViewModel object):

 FrameworkElement element = (FrameworkElement)e.OriginalSource; ItemViewModel item = (ItemViewModel)element.DataContext; 

Then you can get the index of this element in the collection of elements:

 int index = _items.IndexOf(item); 

If you want to get the ListBoxItem itself, you will need to use the VisualHelper class to find the parent hierarchy. Here is the enxtension method that I use for this:

 public static T FindVisualParent<T>(this DependencyObject obj) where T : DependencyObject { DependencyObject parent = VisualTreeHelper.GetParent(obj); while (parent != null) { T t = parent as T; if (t != null) { return t; } parent = VisualTreeHelper.GetParent(parent); } return null; } 

I'm not sure you need this (I could not be sure of your comment), but you can do the following to get the context menu:

 FrameworkElement element = (FrameworkElement)e.OriginalSource; ListBoxItem listItem = element.FindVisualParent<ListBoxItem>(); ContextMenu contextMenu = ContextMenuService.GetContextMenu(listItem); 

This assumes that ContextMenu is bound to the ListBoxItem, if not, then you need to look for another control in the parent hierarchy.

+12
source

var selectedIndex = (sender as ListBox).SelectedIndex;

+1
source

Source: https://habr.com/ru/post/1383059/


All Articles