c# - WPF 列表框 IndexFromPoint

标签 c# wpf wpf-controls

我正在 WPF 列表框之间执行拖放操作,我希望能够在拖放位置而不是列表末尾处插入到集合中。

有人知道类似于 WinForms ListBox IndexFromPoint 函数的解决方案吗?

最佳答案

我最终通过组合使用 DragDropEvent.GetPosition、VisualTreeHelper.GetDescendantBounds 和 Rect.Contains 完成了这项工作。这是我想出的:

int index = -1;
for (int i = 0; i < collection.Count; i++)
{
   var lbi = listBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
   if (lbi == null) continue;
   if (IsMouseOverTarget(lbi, e.GetPosition((IInputElement)lbi)))
   {
       index = i;
       break;
   }
}

代码驻留在 ListBox Drop 事件中。 e 对象是传递给 Drop 事件的 DragEventArgs 对象。

IsMouseOverTarget 的实现是:

private static bool IsMouseOverTarget(Visual target, Point point)
{
    var bounds = VisualTreeHelper.GetDescendantBounds(target);
    return bounds.Contains(point);
}

关于c# - WPF 列表框 IndexFromPoint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6961963/

相关文章:

WPF。如何只显示大 Canvas 的一部分?

WPF 在其他 ControlTemplates 中重用模板

c# - WPF IDataErrorInfo 问题

WPF ObservableCollection 编辑模式

c# - 如何在更改值后在运行时保存 ScriptableObject

wpf - 如何让 WPF 在初始显示控件时不显示验证错误?

WPF:将属性更改连接到动画?

c# - 枚举哈希集并从中删除元素

c# - 具有折叠/展开功能的控件 TreeView

c# - 更改 ComboBox 的验证样式 WPF