How to implement Hold in Listbox?

放肆的年华 提交于 2019-12-03 21:10:27

问题


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;



来源:https://stackoverflow.com/questions/8269244/how-to-implement-hold-in-listbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!