Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações. |
Tradução
Original
|
Classe ListViewInsertionMark
Usado para indicar o local de destino esperado quando um item é arrastado para uma nova posição em um ListView controle. Essa funcionalidade está disponível somente no Windows XP e versões posteriores.
Assembly: System.Windows.Forms (em System.Windows.Forms.dll)
Você pode recuperar um ListViewInsertionMark do InsertionMark propriedade de um ListView controle e usá-lo para indicar visualmente o local de destino esperado em uma operação de do tipo arrastar e soltar quando um item é arrastado para uma nova posição.
Este recurso funciona somente quando o ListView.AutoArrange propriedade é conjunto para true e quando o ListView controle não é classificados automaticamente os itens. Para impedir a classificação automático, a ListView.Sorting propriedade deve ser definida SortOrder.None e o ListView.View propriedade deve ser definida View.LargeIcon, View.SmallIcon, ou View.Tile. Além disso, o recurso de marca de inserção não pode ser usado com o ListView recurso de agrupamento porque o recurso de agrupamento ordena os itens pela associação no agrupar.
The ListViewInsertionMark classe geralmente é usada em um manipulador para o Control.DragOver ou Control.MouseMove evento atualização a posição da inserção marcar sistema autônomo um item é arrastado. Também é usado em um manipulador para o Control.DragDrop ou Control.MouseUp evento para inserir um item arrastado na localização correta.
Para atualizar a posição da marca de inserção, execute as seguintes etapas:
-
Em um manipulador para o Control.DragOver ou Control.MouseMove evento, use o ListView.InsertionMark propriedade para acessar o ListViewInsertionMark objeto associado com o ListView controle.
-
Use o NearestIndex método para recuperar o índice do item mais próximo o ponteiro do mouse.
-
Passar o valor de índice para o ListView.GetItemRect método para recuperar o retângulo delimitador do item.
-
Se o ponteiro do mouse estiver localizado à esquerda do ponto médio do retângulo envolvente, conjunto o AppearsAfterItem propriedade para false; Caso contrário, conjunto para true.
-
conjunto o Index propriedade com o valor de índice recuperado das NearestIndex método. A marca de inserção aparece próxima ao item com o índice especificado à esquerda ou direita, dependendo do AppearsAfterItem valor da propriedade. Se um item é arrastado sobre si mesmo, o índice é -1 e a marca de inserção está oculto.
Para inserir o item arrastado na localização correta, execute as seguintes etapas:
-
Em um manipulador para o Control.DragDrop ou Control.MouseUp evento, use o Index propriedade para determinar o local corrente da marca de inserção. Armazene esse valor a ser usado posteriormente sistema autônomo um índice de inserção.
-
Se o AppearsAfterItem propriedade é conjunto para true, incrementar o valor de índice armazenados inserção.
-
Use o ListView.ListViewItemCollection.Insert método para inserir um clone do item arrastado para a ListView.Items coleção no índice de inserção armazenado.
-
Use o ListView.ListViewItemCollection.Remove método para remover a cópia original do item arrastado.
Você deve inserir um clone do item arrastado antes da cópia original é removida para que o índice de valores no ListView.Items coleção não são alterados antes da inserção.
Para garantir que sistema autônomo itens são exibidos na mesma ordem sistema autônomo seus valores de índice, você deve conjunto o ListView.ListViewItemSorter propriedade para uma implementação das IComparer interface que classifica itens pelo valor de índice. Para obter mais informações, consulte a seção exemplo.
Você pode modificar a cor da marca de inserção usando o Color propriedade. Se precisar de dimensionar ou posição da marca de inserção, você pode obter o retângulo delimitador através de Bounds propriedade.
Observação:
|
|---|
|
O recurso de marca de inserção está disponível somente no Windows XP e a família Windows servidor 2003 quando o aplicativo chama o Application.EnableVisualStyles método. Em sistemas operacionais anteriores, qualquer código relacionadas à marca de inserção será ignorado e a marca de inserção não aparecerá. sistema autônomo resultado, qualquer código que depende o recurso de marca de inserção pode não funcionar corretamente. Você pode desejar incluir um teste determina se o recurso de marca de inserção está disponível e fornecem funcionalidade alternativa quando não estiver disponível. Por exemplo, convém ignorar a todo o código que implementa o item de do tipo arrastar e soltar reposicionamento quando executado em sistemas operacionais que não oferecem suporte a marcas de inserção. O recurso de marca de inserção é fornecido pela mesma biblioteca que fornece o recurso de temas do sistema operacional. Para verificar a disponibilidade desta biblioteca telefonar o FeatureSupport.IsPresent(Object) método de sobrecarga e passar a OSFeature.Themes valor. |
O exemplo de código a seguir demonstra como usar o ListView recurso de marca de inserção e reordenação de item de do tipo arrastar e soltar implementa usando o padrão arrastar eventos. A posição da marca de inserção é atualizada em um manipulador para o Control.DragOver evento. Nesse manipulador, a posição do ponteiro do mouse é comparado com o ponto médio do item mais próximo e o resultado é usado para determinar se parece a marca de inserção para a esquerda ou direita do item.
using System; using System.Drawing; using System.Windows.Forms; publicclass 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] staticvoid Main() { Application.EnableVisualStyles(); Application.Run(new ListViewInsertionMarkExample()); } // Starts the drag-and-drop operation when an item is dragged.privatevoid myListView_ItemDrag(object sender, ItemDragEventArgs e) { myListView.DoDragDrop(e.Item, DragDropEffects.Move); } // Sets the target drop effect.privatevoid myListView_DragEnter(object sender, DragEventArgs e) { e.Effect = e.AllowedEffect; } // Moves the insertion mark as the item is dragged.privatevoid 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.privatevoid myListView_DragLeave(object sender, EventArgs e) { myListView.InsertionMark.Index = -1; } // Moves the item to the location of the insertion mark.privatevoid 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.privateclass ListViewIndexComparer : System.Collections.IComparer { publicint Compare(object x, object y) { return ((ListViewItem)x).Index - ((ListViewItem)y).Index; } } }
import System.*;
import System.Drawing.*;
import System.Windows.Forms.*;
public class ListViewInsertionMarkExample extends Form
{
private ListView myListView;
public ListViewInsertionMarkExample()
{
// Initialize myListView.
myListView = new ListView();
myListView.set_Dock(DockStyle.Fill);
myListView.set_View(View.LargeIcon);
myListView.set_MultiSelect(false);
myListView.set_ListViewItemSorter(new ListViewIndexComparer());
// Initialize the insertion mark.
myListView.get_InsertionMark().set_Color(Color.get_Green());
// Add items to myListView.
myListView.get_Items().Add("zero");
myListView.get_Items().Add("one");
myListView.get_Items().Add("two");
myListView.get_Items().Add("three");
myListView.get_Items().Add("four");
myListView.get_Items().Add("five");
// Initialize the drag-and-drop operation when running
// under Windows XP or a later operating system.
if (System.Environment.get_OSVersion().get_Version().get_Major() > 5
|| (System.Environment.get_OSVersion().get_Version().get_Major()
== 5 && System.Environment.get_OSVersion().get_Version().
get_Minor() >= 1)) {
myListView.set_AllowDrop(true);
myListView.add_ItemDrag(new ItemDragEventHandler(
myListView_ItemDrag));
myListView.add_DragEnter(new DragEventHandler(
myListView_DragEnter));
myListView.add_DragOver(new DragEventHandler(myListView_DragOver));
myListView.add_DragLeave(new EventHandler(myListView_DragLeave));
myListView.add_DragDrop(new DragEventHandler(myListView_DragDrop));
}
// Initialize the form.
this.set_Text("ListView Insertion Mark Example");
this.get_Controls().Add(myListView);
} //ListViewInsertionMarkExample
/** @attribute STAThread()
*/
public static void main(String[] args)
{
Application.Run(new ListViewInsertionMarkExample());
} //main
// Starts the drag-and-drop operation when an item is dragged.
private void myListView_ItemDrag(Object sender, ItemDragEventArgs e)
{
myListView.DoDragDrop(e.get_Item(), DragDropEffects.Move);
} //myListView_ItemDrag
// Sets the target drop effect.
private void myListView_DragEnter(Object sender, DragEventArgs e)
{
e.set_Effect(e.get_AllowedEffect());
} //myListView_DragEnter
// 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.get_X(), e.get_Y()));
// Retrieve the index of the item closest to the mouse pointer.
int targetIndex = myListView.get_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.get_X() > itemBounds.get_Left()
+ itemBounds.get_Width() / 2) {
myListView.get_InsertionMark().set_AppearsAfterItem(true);
}
else {
myListView.get_InsertionMark().set_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.get_InsertionMark().set_Index(targetIndex);
} //myListView_DragOver
// Removes the insertion mark when the mouse leaves the control.
private void myListView_DragLeave(Object sender, EventArgs e)
{
myListView.get_InsertionMark().set_Index(-1);
} //myListView_DragLeave
// 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.get_InsertionMark().get_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.get_InsertionMark().get_AppearsAfterItem()) {
targetIndex++;
}
// Retrieve the dragged item.
ListViewItem draggedItem = (ListViewItem)(e.get_Data().GetData(
ListViewItem.class.ToType()));
// 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.get_Items().Insert(targetIndex, (ListViewItem)
draggedItem.Clone());
// Remove the original copy of the dragged item.
myListView.get_Items().Remove(draggedItem);
} //myListView_DragDrop
// Sorts ListViewItem objects by index.
private class ListViewIndexComparer
implements System.Collections.IComparer
{
public int Compare(Object x, Object y)
{
return ((ListViewItem)x).get_Index()
- ((ListViewItem)y).get_Index();
} //Compare
} //ListViewIndexComparer
} //ListViewInsertionMarkExample
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98
o.NET Framework e.NET Compact Framework não oferecem suporte a todas as versões de cada plataforma. Para obter uma lista de versões suportadas, consulte Requisitos de sistema do .NET framework.
Observação: