簡體   English   中英

在WPF C#中的ListView中將項目拖放到特定索引中

[英]Drop Item into Specific Index in ListView in WPF C#

我在WPF中的ListView中有一個文件列表。 用戶可以將文件拖到列表視圖中,現在它們只是附加到列表的末尾。 是否可以將文件插入到用戶放置的ListView中?

WPF並非真正設計為以這種方式使用。 雖然你可以強力將ListViewItem直接添加到ListView,但它真正應該工作的方式是你有一些類型的集合( ObservableCollection<FileInfo>可以正常工作)並將ListView的ItemsSource屬性綁定到該集合。

那么答案很簡單。 您可以使用帶有索引的集合的Insert方法,而不是Add方法。

至於查找鼠標事件發生的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大師。 它可能不是你想要的,但它應該非常接近。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM