我在 WPF 的 ListView 中有一个文件列表。用户可以将文件拖到列表视图中,现在它们只是附加到列表的末尾。是否可以将文件插入到用户放置它的 ListView 中?
3 回答
WPF 并不是真正设计为以这种方式使用的。虽然您可以强制将 ListViewItem 直接添加到 ListView,但它真正应该工作的方式是您拥有某种集合(ObservableCollection<FileInfo>
会很好)并将 ListView 的 ItemsSource 属性绑定到该集合。
那么答案很简单。代替 Add 方法,您使用带有索引的集合的 Insert 方法。
至于查找鼠标事件发生在哪个 ListViewItem 上,您可以使用VisualTreeHelper.HitTest方法。
从我的角度来看,当我使用模板项目时有点棘手。我和它打了一点点。我正在分享与 DraggableListBox 一起使用的用例。但我想同样的解决方案适用于 ListBox 控件。
作为第一个我创建了能够为我提供 ListItem 元素的依赖对象扩展:
public static class WpfDomHelper
{
public static T FindParent<T>(this DependencyObject child) where T : DependencyObject
{
DependencyObject parentObject = VisualTreeHelper.GetParent(child);
if (parentObject == null) return null;
T parent = parentObject as T;
if (parent != null)
return parent;
else
return FindParent<T>(parentObject);
}
}
然后我实现了 Drop 逻辑,该逻辑根据目标 ListBoxItems 的特定 Drop Y 位置插入(添加)项目:
private void Grid_Drop(object sender, DragEventArgs e)
{
int dropIndex = -1; // default position directong to add() call
// checking drop destination position
Point pt = e.GetPosition((UIElement)sender);
HitTestResult result = VisualTreeHelper.HitTest(this, pt);
if (result != null && result.VisualHit != null)
{
// checking the object behin the drop position (Item type depend)
var theOne = result.VisualHit.FindParent<Microsoft.TeamFoundation.Controls.WPF.DraggableListBoxItem>();
// identifiing the position according bound view model (context of item)
if (theOne != null)
{
//identifing the position of drop within the item
var itemCenterPosY = theOne.ActualHeight / 2;
var dropPosInItemPos = e.GetPosition(theOne);
// geting the index
var itemIndex = tasksListBox.Items.IndexOf(theOne.Content);
// decission if insert before or below
if (dropPosInItemPos.Y > itemCenterPosY)
{ // when drag is gropped in second half the item is inserted bellow
itemIndex = itemIndex + 1;
}
dropIndex = itemIndex;
}
}
.... here create the item .....
if (dropIndex < 0)
ViewModel.Items.Add(item);
else
ViewModel.Items.Insert(dropIndex, item);
e.Handled = true;
}
所以这个解决方案适用于我的模板 DraggableListBoxView,我想同样的解决方案必须适用于标准 ListBoxView。祝你好运
你可以这样做。这需要一些工作,但可以做到。那里有几个演示,这里是 CodeProject 上的一个。这个特别的由被称为 Josh Smith的wpf 大师编写。它可能不是您正在寻找的东西,但它应该非常接近。