ListViewInsertionMark Класс
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Используется для указания ожидаемого расположения удаления при перетаскивании элемента в новое положение элемента ListView управления. Эта функция доступна только в Windows XP и более поздних версиях.
public ref class ListViewInsertionMark sealed
public sealed class ListViewInsertionMark
type ListViewInsertionMark = class
Public NotInheritable Class ListViewInsertionMark
- Наследование
-
ListViewInsertionMark
Примеры
В следующем примере кода показано, как использовать ListView функцию метки вставки и реализовать переупорядочение элементов перетаскивания с помощью стандартных событий перетаскивания. Позиция метки вставки обновляется в обработчике Control.DragOver события. В этом обработчике позиция указателя мыши сравнивается с серединой ближайшего элемента, а результат используется для определения того, отображается ли знак вставки слева или справа от элемента.
#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>
using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;
public ref class ListViewInsertionMarkExample: public Form
{
private:
ListView^ myListView;
public:
ListViewInsertionMarkExample()
{
// Initialize myListView.
myListView = gcnew ListView;
myListView->Dock = DockStyle::Fill;
myListView->View = View::LargeIcon;
myListView->MultiSelect = false;
myListView->ListViewItemSorter = gcnew ListViewIndexComparer;
// Initialize the insertion mark.
myListView->InsertionMark->Color = Color::Green;
// Add items to myListView.
myListView->Items->Add( "zero" );
myListView->Items->Add( "one" );
myListView->Items->Add( "two" );
myListView->Items->Add( "three" );
myListView->Items->Add( "four" );
myListView->Items->Add( "five" );
// Initialize the drag-and-drop operation when running
// under Windows XP or a later operating system.
if ( System::Environment::OSVersion->Version->Major > 5 || (System::Environment::OSVersion->Version->Major == 5 && System::Environment::OSVersion->Version->Minor >= 1) )
{
myListView->AllowDrop = true;
myListView->ItemDrag += gcnew ItemDragEventHandler( this, &ListViewInsertionMarkExample::myListView_ItemDrag );
myListView->DragEnter += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragEnter );
myListView->DragOver += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragOver );
myListView->DragLeave += gcnew EventHandler( this, &ListViewInsertionMarkExample::myListView_DragLeave );
myListView->DragDrop += gcnew DragEventHandler( this, &ListViewInsertionMarkExample::myListView_DragDrop );
}
// Initialize the form.
this->Text = "ListView Insertion Mark Example";
this->Controls->Add( myListView );
}
private:
// Starts the drag-and-drop operation when an item is dragged.
void myListView_ItemDrag( Object^ /*sender*/, ItemDragEventArgs^ e )
{
myListView->DoDragDrop( e->Item, DragDropEffects::Move );
}
// Sets the target drop effect.
void myListView_DragEnter( Object^ /*sender*/, DragEventArgs^ e )
{
e->Effect = e->AllowedEffect;
}
// Moves the insertion mark as the item is dragged.
void myListView_DragOver( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the client coordinates of the mouse pointer.
Point targetPoint = myListView->PointToClient( Point(e->X,e->Y) );
// Retrieve the index of the item closest to the mouse pointer.
int targetIndex = myListView->InsertionMark->NearestIndex( targetPoint );
// Confirm that the mouse pointer is not over the dragged item.
if ( targetIndex > -1 )
{
// Determine whether the mouse pointer is to the left or
// the right of the midpoint of the closest item and set
// the InsertionMark.AppearsAfterItem property accordingly.
Rectangle itemBounds = myListView->GetItemRect( targetIndex );
if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
{
myListView->InsertionMark->AppearsAfterItem = true;
}
else
{
myListView->InsertionMark->AppearsAfterItem = false;
}
}
// Set the location of the insertion mark. If the mouse is
// over the dragged item, the targetIndex value is -1 and
// the insertion mark disappears.
myListView->InsertionMark->Index = targetIndex;
}
// Removes the insertion mark when the mouse leaves the control.
void myListView_DragLeave( Object^ /*sender*/, EventArgs^ /*e*/ )
{
myListView->InsertionMark->Index = -1;
}
// Moves the item to the location of the insertion mark.
void myListView_DragDrop( Object^ /*sender*/, DragEventArgs^ e )
{
// Retrieve the index of the insertion mark;
int targetIndex = myListView->InsertionMark->Index;
// If the insertion mark is not visible, exit the method.
if ( targetIndex == -1 )
{
return;
}
// If the insertion mark is to the right of the item with
// the corresponding index, increment the target index.
if ( myListView->InsertionMark->AppearsAfterItem )
{
targetIndex++;
}
// Retrieve the dragged item.
ListViewItem^ draggedItem = dynamic_cast<ListViewItem^>(e->Data->GetData( ListViewItem::typeid ));
// Insert a copy of the dragged item at the target index.
// A copy must be inserted before the original item is removed
// to preserve item index values.
myListView->Items->Insert( targetIndex, dynamic_cast<ListViewItem^>(draggedItem->Clone()) );
// Remove the original copy of the dragged item.
myListView->Items->Remove( draggedItem );
}
// Sorts ListViewItem objects by index.
ref class ListViewIndexComparer: public System::Collections::IComparer
{
public:
virtual int Compare( Object^ x, Object^ y )
{
return (dynamic_cast<ListViewItem^>(x))->Index - (dynamic_cast<ListViewItem^>(y))->Index;
}
};
};
[STAThread]
int main()
{
Application::EnableVisualStyles();
Application::Run( gcnew ListViewInsertionMarkExample );
}
using System;
using System.Drawing;
using System.Windows.Forms;
public class ListViewInsertionMarkExample : Form
{
private ListView myListView;
public ListViewInsertionMarkExample()
{
// Initialize myListView.
myListView = new ListView();
myListView.Dock = DockStyle.Fill;
myListView.View = View.LargeIcon;
myListView.MultiSelect = false;
myListView.ListViewItemSorter = new ListViewIndexComparer();
// Initialize the insertion mark.
myListView.InsertionMark.Color = Color.Green;
// Add items to myListView.
myListView.Items.Add("zero");
myListView.Items.Add("one");
myListView.Items.Add("two");
myListView.Items.Add("three");
myListView.Items.Add("four");
myListView.Items.Add("five");
// Initialize the drag-and-drop operation when running
// under Windows XP or a later operating system.
if (OSFeature.Feature.IsPresent(OSFeature.Themes))
{
myListView.AllowDrop = true;
myListView.ItemDrag += new ItemDragEventHandler(myListView_ItemDrag);
myListView.DragEnter += new DragEventHandler(myListView_DragEnter);
myListView.DragOver += new DragEventHandler(myListView_DragOver);
myListView.DragLeave += new EventHandler(myListView_DragLeave);
myListView.DragDrop += new DragEventHandler(myListView_DragDrop);
}
// Initialize the form.
this.Text = "ListView Insertion Mark Example";
this.Controls.Add(myListView);
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.Run(new ListViewInsertionMarkExample());
}
// Starts the drag-and-drop operation when an item is dragged.
private void myListView_ItemDrag(object sender, ItemDragEventArgs e)
{
myListView.DoDragDrop(e.Item, DragDropEffects.Move);
}
// Sets the target drop effect.
private void myListView_DragEnter(object sender, DragEventArgs e)
{
e.Effect = e.AllowedEffect;
}
// Moves the insertion mark as the item is dragged.
private void myListView_DragOver(object sender, DragEventArgs e)
{
// Retrieve the client coordinates of the mouse pointer.
Point targetPoint =
myListView.PointToClient(new Point(e.X, e.Y));
// Retrieve the index of the item closest to the mouse pointer.
int targetIndex = myListView.InsertionMark.NearestIndex(targetPoint);
// Confirm that the mouse pointer is not over the dragged item.
if (targetIndex > -1)
{
// Determine whether the mouse pointer is to the left or
// the right of the midpoint of the closest item and set
// the InsertionMark.AppearsAfterItem property accordingly.
Rectangle itemBounds = myListView.GetItemRect(targetIndex);
if ( targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) )
{
myListView.InsertionMark.AppearsAfterItem = true;
}
else
{
myListView.InsertionMark.AppearsAfterItem = false;
}
}
// Set the location of the insertion mark. If the mouse is
// over the dragged item, the targetIndex value is -1 and
// the insertion mark disappears.
myListView.InsertionMark.Index = targetIndex;
}
// Removes the insertion mark when the mouse leaves the control.
private void myListView_DragLeave(object sender, EventArgs e)
{
myListView.InsertionMark.Index = -1;
}
// Moves the item to the location of the insertion mark.
private void myListView_DragDrop(object sender, DragEventArgs e)
{
// Retrieve the index of the insertion mark;
int targetIndex = myListView.InsertionMark.Index;
// If the insertion mark is not visible, exit the method.
if (targetIndex == -1)
{
return;
}
// If the insertion mark is to the right of the item with
// the corresponding index, increment the target index.
if (myListView.InsertionMark.AppearsAfterItem)
{
targetIndex++;
}
// Retrieve the dragged item.
ListViewItem draggedItem =
(ListViewItem)e.Data.GetData(typeof(ListViewItem));
// Insert a copy of the dragged item at the target index.
// A copy must be inserted before the original item is removed
// to preserve item index values.
myListView.Items.Insert(
targetIndex, (ListViewItem)draggedItem.Clone());
// Remove the original copy of the dragged item.
myListView.Items.Remove(draggedItem);
}
// Sorts ListViewItem objects by index.
private class ListViewIndexComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
return ((ListViewItem)x).Index - ((ListViewItem)y).Index;
}
}
}
Imports System.Drawing
Imports System.Windows.Forms
Public Class ListViewInsertionMarkExample
Inherits Form
Private myListView As ListView
Public Sub New()
' Initialize myListView.
myListView = New ListView()
myListView.Dock = DockStyle.Fill
myListView.View = View.LargeIcon
myListView.MultiSelect = False
myListView.ListViewItemSorter = New ListViewIndexComparer()
' Initialize the insertion mark.
myListView.InsertionMark.Color = Color.Green
' Add items to myListView.
myListView.Items.Add("zero")
myListView.Items.Add("one")
myListView.Items.Add("two")
myListView.Items.Add("three")
myListView.Items.Add("four")
myListView.Items.Add("five")
' Initialize the drag-and-drop operation when running
' under Windows XP or a later operating system.
If OSFeature.Feature.IsPresent(OSFeature.Themes)
myListView.AllowDrop = True
AddHandler myListView.ItemDrag, AddressOf myListView_ItemDrag
AddHandler myListView.DragEnter, AddressOf myListView_DragEnter
AddHandler myListView.DragOver, AddressOf myListView_DragOver
AddHandler myListView.DragLeave, AddressOf myListView_DragLeave
AddHandler myListView.DragDrop, AddressOf myListView_DragDrop
End If
' Initialize the form.
Me.Text = "ListView Insertion Mark Example"
Me.Controls.Add(myListView)
End Sub
<STAThread()> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New ListViewInsertionMarkExample())
End Sub
' Starts the drag-and-drop operation when an item is dragged.
Private Sub myListView_ItemDrag(sender As Object, e As ItemDragEventArgs)
myListView.DoDragDrop(e.Item, DragDropEffects.Move)
End Sub
' Sets the target drop effect.
Private Sub myListView_DragEnter(sender As Object, e As DragEventArgs)
e.Effect = e.AllowedEffect
End Sub
' Moves the insertion mark as the item is dragged.
Private Sub myListView_DragOver(sender As Object, e As DragEventArgs)
' Retrieve the client coordinates of the mouse pointer.
Dim targetPoint As Point = myListView.PointToClient(New Point(e.X, e.Y))
' Retrieve the index of the item closest to the mouse pointer.
Dim targetIndex As Integer = _
myListView.InsertionMark.NearestIndex(targetPoint)
' Confirm that the mouse pointer is not over the dragged item.
If targetIndex > -1 Then
' Determine whether the mouse pointer is to the left or
' the right of the midpoint of the closest item and set
' the InsertionMark.AppearsAfterItem property accordingly.
Dim itemBounds As Rectangle = myListView.GetItemRect(targetIndex)
If targetPoint.X > itemBounds.Left + (itemBounds.Width / 2) Then
myListView.InsertionMark.AppearsAfterItem = True
Else
myListView.InsertionMark.AppearsAfterItem = False
End If
End If
' Set the location of the insertion mark. If the mouse is
' over the dragged item, the targetIndex value is -1 and
' the insertion mark disappears.
myListView.InsertionMark.Index = targetIndex
End Sub
' Removes the insertion mark when the mouse leaves the control.
Private Sub myListView_DragLeave(sender As Object, e As EventArgs)
myListView.InsertionMark.Index = -1
End Sub
' Moves the item to the location of the insertion mark.
Private Sub myListView_DragDrop(sender As Object, e As DragEventArgs)
' Retrieve the index of the insertion mark;
Dim targetIndex As Integer = myListView.InsertionMark.Index
' If the insertion mark is not visible, exit the method.
If targetIndex = -1 Then
Return
End If
' If the insertion mark is to the right of the item with
' the corresponding index, increment the target index.
If myListView.InsertionMark.AppearsAfterItem Then
targetIndex += 1
End If
' Retrieve the dragged item.
Dim draggedItem As ListViewItem = _
CType(e.Data.GetData(GetType(ListViewItem)), ListViewItem)
' Insert a copy of the dragged item at the target index.
' A copy must be inserted before the original item is removed
' to preserve item index values.
myListView.Items.Insert(targetIndex, _
CType(draggedItem.Clone(), ListViewItem))
' Remove the original copy of the dragged item.
myListView.Items.Remove(draggedItem)
End Sub
' Sorts ListViewItem objects by index.
Private Class ListViewIndexComparer
Implements System.Collections.IComparer
Public Function Compare(x As Object, y As Object) As Integer _
Implements System.Collections.IComparer.Compare
Return CType(x, ListViewItem).Index - CType(y, ListViewItem).Index
End Function 'Compare
End Class
End Class
Комментарии
Вы можете получить ListViewInsertionMark из InsertionMark свойства элемента управления и использовать его для визуального указания ожидаемого ListView расположения перетаскивания в операции перетаскивания при перетаскивании элемента в новое положение.
Эта функция работает только в том случае, если ListView.AutoArrange для свойства задано true значение и когда ListView элемент управления не сортирует элементы автоматически. Чтобы предотвратить автоматическую сортировку, ListView.Sorting свойство должно быть задано ListView.ViewSortOrder.None и свойство должно иметь значение View.LargeIcon, View.SmallIconили View.Tile. Кроме того, компонент метки вставки нельзя использовать с ListView функцией группировки, так как компонент группировки упорядочивает элементы по членству в группах.
ListViewInsertionMark Класс обычно используется в обработчике для Control.DragOver события или Control.MouseMove для обновления позиции метки вставки, так как элемент перетаскивается. Он также используется в обработчике для или Control.MouseUp события для Control.DragDrop вставки перетаскиваемого элемента в правильное расположение.
Чтобы обновить позицию метки вставки, выполните следующие действия.
В обработчике или событии используйте ListView.InsertionMark свойство для Control.DragOverControl.MouseMove доступа к ListViewInsertionMark объекту, связанному с элементом ListView управления.
NearestIndex Используйте метод для получения индекса элемента, ближайшего к указателю мыши.
Передайте значение ListView.GetItemRect индекса методу, чтобы получить ограничивающий прямоугольник элемента.
Если указатель мыши расположен слева от средней точки ограничивающего прямоугольника, задайте AppearsAfterItem для свойства
falseзначение ; в противном случае задайте для него значениеtrue.Index Задайте для свойства значение индекса, полученное NearestIndex из метода. Знак вставки отображается рядом с элементом с указанным индексом слева или справа в зависимости от AppearsAfterItem значения свойства. Если элемент перетаскивается по себе, индекс -1, а метка вставки скрыта.
Чтобы вставить перетаскиваемый элемент в правильное расположение, выполните следующие действия:
В обработчике для события используйте Control.MouseUpIndex свойство, Control.DragDrop чтобы определить текущее расположение метки вставки. Сохраните это значение позже в качестве индекса вставки.
AppearsAfterItem Если для свойства задано
trueзначение, увеличьте значение сохраненного индекса вставки.ListView.ListViewItemCollection.Insert Используйте метод для вставки клона перетаскиваемого элемента в ListView.Items коллекцию в хранимом индексе вставки.
ListView.ListViewItemCollection.Remove Используйте метод, чтобы удалить исходную копию перетаскиваемого элемента.
Перед удалением исходной копии необходимо вставить клон перетаскиваемого элемента, чтобы значения индекса в ListView.Items коллекции не изменялись перед вставкой.
Чтобы элементы отображались в том же порядке, что и их значения индекса, необходимо задать ListView.ListViewItemSorter свойство IComparer реализации интерфейса, который сортирует элементы по значению индекса. Дополнительные сведения см. в разделе "Пример".
Цвет метки вставки можно изменить с помощью Color свойства. Если вам нужен размер или положение метки вставки, можно получить его ограничивающий прямоугольник через Bounds свойство.
Замечание
Функция метки вставки доступна только в Windows XP и семействе Windows Server 2003, когда приложение вызывает Application.EnableVisualStyles метод. В предыдущих операционных системах любой код, связанный с меткой вставки, будет игнорироваться, и метка вставки не будет отображаться. В результате любой код, зависящий от функции метки вставки, может работать неправильно. Возможно, потребуется включить тест, определяющий, доступна ли функция метки вставки и предоставить альтернативные функции, если она недоступна. Например, может потребоваться обойти весь код, реализующий изменение положения элемента перетаскивания при выполнении в операционных системах, которые не поддерживают метки вставки.
Функция метки вставки предоставляется той же библиотекой, которая предоставляет функцию тем операционной системы. Чтобы проверить доступность этой библиотеки, вызовите перегрузку метода и передайте FeatureSupport.IsPresent(Object)OSFeature.Themes значение.
Свойства
| Имя | Описание |
|---|---|
| AppearsAfterItem |
Возвращает или задает значение, указывающее, отображается ли знак вставки справа от элемента с индексом, указанным свойством Index . |
| Bounds |
Возвращает ограничивающий прямоугольник знака вставки. |
| Color |
Возвращает или задает цвет метки вставки. |
| Index |
Возвращает или задает индекс элемента рядом с которым отображается знак вставки. |
Методы
| Имя | Описание |
|---|---|
| Equals(Object) |
Определяет, равен ли указанный объект текущему объекту. (Унаследовано от Object) |
| GetHashCode() |
Служит хэш-функцией по умолчанию. (Унаследовано от Object) |
| GetType() |
Возвращает Type текущего экземпляра. (Унаследовано от Object) |
| MemberwiseClone() |
Создает неглубокую копию текущей Object. (Унаследовано от Object) |
| NearestIndex(Point) |
Извлекает индекс элемента, ближайшего к указанной точке. |
| ToString() |
Возвращает строку, представляющую текущий объект. (Унаследовано от Object) |