How to implement Hold in Listbox?

2019-02-14 15:15发布

问题:

If hold the listbox, I want to get listbox index.

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 to do this.

回答1:

e.OriginalSource will get you the actual control that was held (the top-most control directly under your finger). Depending on your ItemTemplate and where you hold then this could be any of the controls in the item. You can then check the DataContext of this control to get the object that is bound to that item (going by your comment this will be an ItemViewModel object):

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

You can then get the index of this item in the items collection:

int index = _items.IndexOf(item);

If you want to get the ListBoxItem itself you will need to use the VisualHelper class to search the parent heirarchy. Here is an enxtension method that I use to do 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 if you need this (I couldn't be sure from your comment) but you can then 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 the ContextMenu is attached to the ListBoxItem, if not then you need to search for a different control in the parent heirarchy.



回答2:

var selectedIndex = (sender as ListBox).SelectedIndex;