如何在 Listbox 中实现 Hold? [英] How to implement Hold in Listbox?

查看:16
本文介绍了如何在 Listbox 中实现 Hold?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果持有列表框,我想获取列表框索引.

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

这是我的代码:

<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.

推荐答案

e.OriginalSource 将为您提供实际的控制权(直接在您手指下的最顶层控制权).根据您的 ItemTemplate 和您持有的位置,这可能是项目中的任何控件.然后,您可以检查此控件的 DataContext 以获取绑定到该项目的对象(根据您的评论,这将是一个 ItemViewModel 对象):

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;

然后就可以在items集合中获取这个item的索引了:

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

int index = _items.IndexOf(item);

如果您想获取 ListBoxItem 本身,您将需要使用 VisualHelper 类来搜索父层次结构.这是我用来执行此操作的扩展方法:

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);

这假设 ContextMenu 附加到 ListBoxItem,否则您需要在父层次结构中搜索不同的控件.

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.

这篇关于如何在 Listbox 中实现 Hold?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆