ListView.VirtualMode ListView.VirtualMode ListView.VirtualMode ListView.VirtualMode Property

Définition

Obtient ou définit une valeur indiquant si vous avez fourni vos propres opérations de gestion de données pour le contrôle ListView.Gets or sets a value indicating whether you have provided your own data-management operations for the ListView control.

public:
 property bool VirtualMode { bool get(); void set(bool value); };
public bool VirtualMode { get; set; }
member this.VirtualMode : bool with get, set
Public Property VirtualMode As Boolean

Valeur de propriété

true Si ListView utilise des opérations de gestion de données que vous fournissez ; sinon, false.true if ListView uses data-management operations that you provide; otherwise, false. La valeur par défaut est false.The default is false.

Exceptions

VirtualMode a la valeur true et l’une des conditions suivantes existe :VirtualMode is set to true and one of the following conditions exist:

  • VirtualListSize is greater than 0 and RetrieveVirtualItem is not handled.
  • ou-or-

  • Items, CheckedItems, or SelectedItems contains items.
  • ou-or- - Des modifications sont apportées à Items.- Edits are made to Items.

    Exemples

    Cet exemple illustre une simple ListView dont le contenu est de 10 000 premiers carrés.This example illustrates a simple ListView whose contents are the first ten thousand squares. Il gère la recherche et utilise un cache pour améliorer les performances.It handles searching and uses a cache for increased performance.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Text;
    using System.Windows.Forms;
    
    public class Form1 : Form
    {
        private ListViewItem[] myCache; //array to cache items for the virtual list
        private int firstItem; //stores the index of the first item in the cache
    
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    
        public Form1()
        {
            //Create a simple ListView.
            ListView listView1 = new ListView();
            listView1.View = View.SmallIcon;
            listView1.VirtualMode = true;
            listView1.VirtualListSize = 10000;
    
            //Hook up handlers for VirtualMode events.
            listView1.RetrieveVirtualItem += new RetrieveVirtualItemEventHandler(listView1_RetrieveVirtualItem);
            listView1.CacheVirtualItems += new CacheVirtualItemsEventHandler(listView1_CacheVirtualItems);
            listView1.SearchForVirtualItem += new SearchForVirtualItemEventHandler(listView1_SearchForVirtualItem);
    
            //Add ListView to the form.
            this.Controls.Add(listView1);
    
            //Search for a particular virtual item.
            //Notice that we never manually populate the collection!
            //If you leave out the SearchForVirtualItem handler, this will return null.
            ListViewItem lvi = listView1.FindItemWithText("111111");
    
            //Select the item found and scroll it into view.
            if (lvi != null)
            {
                listView1.SelectedIndices.Add(lvi.Index);
                listView1.EnsureVisible(lvi.Index);
            }
        }
    
        //The basic VirtualMode function.  Dynamically returns a ListViewItem
        //with the required properties; in this case, the square of the index.
        void listView1_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
        {
            //Caching is not required but improves performance on large sets.
            //To leave out caching, don't connect the CacheVirtualItems event 
            //and make sure myCache is null.
    
            //check to see if the requested item is currently in the cache
            if (myCache != null && e.ItemIndex >= firstItem && e.ItemIndex < firstItem + myCache.Length)
            {
                //A cache hit, so get the ListViewItem from the cache instead of making a new one.
                e.Item = myCache[e.ItemIndex - firstItem];
            }
            else
            {
                //A cache miss, so create a new ListViewItem and pass it back.
                int x = e.ItemIndex * e.ItemIndex;
                e.Item = new ListViewItem(x.ToString());
            }
        }
    
        //Manages the cache.  ListView calls this when it might need a 
        //cache refresh.
        void listView1_CacheVirtualItems(object sender, CacheVirtualItemsEventArgs e)
        {
            //We've gotten a request to refresh the cache.
            //First check if it's really neccesary.
            if (myCache != null && e.StartIndex >= firstItem && e.EndIndex <= firstItem + myCache.Length)
            {
                //If the newly requested cache is a subset of the old cache, 
                //no need to rebuild everything, so do nothing.
                return;
            }
    
            //Now we need to rebuild the cache.
            firstItem = e.StartIndex;
            int length = e.EndIndex - e.StartIndex + 1; //indexes are inclusive
            myCache = new ListViewItem[length];
            
            //Fill the cache with the appropriate ListViewItems.
            int x = 0;
            for (int i = 0; i < length; i++)
            {
                x = (i + firstItem) * (i + firstItem);
                myCache[i] = new ListViewItem(x.ToString());
            }
    
        }
    
        //This event handler enables search functionality, and is called
        //for every search request when in Virtual mode.
        void listView1_SearchForVirtualItem(object sender, SearchForVirtualItemEventArgs e)
        {
            //We've gotten a search request.
            //In this example, finding the item is easy since it's
            //just the square of its index.  We'll take the square root
            //and round.
            double x = 0;
            if (Double.TryParse(e.Text, out x)) //check if this is a valid search
            {
                x = Math.Sqrt(x);
                x = Math.Round(x);
                e.Index = (int)x;
                   
            }
            //If e.Index is not set, the search returns null.
            //Note that this only handles simple searches over the entire
            //list, ignoring any other settings.  Handling Direction, StartIndex,
            //and the other properties of SearchForVirtualItemEventArgs is up
            //to this handler.
        }
    }
    
    Public Class Form1
        Inherits Form
        Private myCache() As ListViewItem 'array to cache items for the virtual list
        Private firstItem As Integer 'stores the index of the first item in the cache
        Private WithEvents listView1 As ListView
    
        Public Shared Sub Main()
            Application.Run(New Form1)
        End Sub
    
        Public Sub New()
            'Create a simple ListView.
            listView1 = New ListView()
            listView1.View = View.SmallIcon
            listView1.VirtualMode = True
            listView1.VirtualListSize = 10000
    
            'Add ListView to the form.
            Me.Controls.Add(listView1)
    
            'Search for a particular virtual item.
            'Notice that we never manually populate the collection!
            'If you leave out the SearchForVirtualItem handler, this will return null.
            Dim lvi As ListViewItem = listView1.FindItemWithText("111111")
    
            'Select the item found and scroll it into view.
            If Not (lvi Is Nothing) Then
                listView1.SelectedIndices.Add(lvi.Index)
                listView1.EnsureVisible(lvi.Index)
            End If
    
        End Sub
    
        'The basic VirtualMode function.  Dynamically returns a ListViewItem
        'with the required properties; in this case, the square of the index.
        Private Sub listView1_RetrieveVirtualItem(ByVal sender As Object, ByVal e As RetrieveVirtualItemEventArgs) Handles listView1.RetrieveVirtualItem
            'Caching is not required but improves performance on large sets.
            'To leave out caching, don't connect the CacheVirtualItems event 
            'and make sure myCache is null.
            'check to see if the requested item is currently in the cache
            If Not (myCache Is Nothing) AndAlso e.ItemIndex >= firstItem AndAlso e.ItemIndex < firstItem + myCache.Length Then
                'A cache hit, so get the ListViewItem from the cache instead of making a new one.
                e.Item = myCache((e.ItemIndex - firstItem))
            Else
                'A cache miss, so create a new ListViewItem and pass it back.
                Dim x As Integer = e.ItemIndex * e.ItemIndex
                e.Item = New ListViewItem(x.ToString())
            End If
    
    
        End Sub
    
        'Manages the cache.  ListView calls this when it might need a 
        'cache refresh.
        Private Sub listView1_CacheVirtualItems(ByVal sender As Object, ByVal e As CacheVirtualItemsEventArgs) Handles listView1.CacheVirtualItems
            'We've gotten a request to refresh the cache.
            'First check if it's really neccesary.
            If Not (myCache Is Nothing) AndAlso e.StartIndex >= firstItem AndAlso e.EndIndex <= firstItem + myCache.Length Then
                'If the newly requested cache is a subset of the old cache, 
                'no need to rebuild everything, so do nothing.
                Return
            End If
    
            'Now we need to rebuild the cache.
            firstItem = e.StartIndex
            Dim length As Integer = e.EndIndex - e.StartIndex + 1 'indexes are inclusive
            myCache = New ListViewItem(length) {}
    
            'Fill the cache with the appropriate ListViewItems.
            Dim x As Integer = 0
            Dim i As Integer
            For i = 0 To length
                x = (i + firstItem) * (i + firstItem)
                myCache(i) = New ListViewItem(x.ToString())
            Next i
    
        End Sub
    
        'This event handler enables search functionality, and is called
        'for every search request when in Virtual mode.
        Private Sub listView1_SearchForVirtualItem(ByVal sender As Object, ByVal e As SearchForVirtualItemEventArgs) Handles listView1.SearchForVirtualItem
            'We've gotten a search request.
            'In this example, finding the item is easy since it's
            'just the square of its index.  We'll take the square root
            'and round.
            Dim x As Double = 0
            If [Double].TryParse(e.Text, x) Then 'check if this is a valid search
                x = Math.Sqrt(x)
                x = Math.Round(x)
                e.Index = Fix(x)
            End If
            'Note that this only handles simple searches over the entire
            'list, ignoring any other settings.  Handling Direction, StartIndex,
            'and the other properties of SearchForVirtualItemEventArgs is up
            'to this handler.
        End Sub
    
    End Class
    

    Remarques

    Définition de la VirtualMode propriété true place le ListView en mode virtuel.Setting the VirtualMode property to true puts the ListView into virtual mode. En mode virtuel, la normale Items collection n’est pas utilisée.In Virtual mode, the normal Items collection is unused. Au lieu de cela, ListViewItem objets sont créés dynamiquement comme le ListView en a besoin.Instead, ListViewItem objects are created dynamically as the ListView requires them.

    Mode virtuel peut être utile dans de nombreuses situations.Virtual mode can be useful under many circumstances. Si un ListView objet doit être rempli à partir d’une très grande collection déjà en mémoire, création d’un ListViewItem de l’objet pour chaque entrée peut être inutile.If a ListView object must be populated from a very large collection already in memory, creating a ListViewItem object for each entry can be wasteful. En mode virtuel, seuls les éléments requis sont créés.In virtual mode, only the items required are created. Dans d’autres cas, les valeurs de la ListViewItem objets peuvent être nécessaire de recalculer fréquemment, et cela pour l’ensemble de la collection produiraient des performances inacceptables.In other cases, the values of the ListViewItem objects may need to be recalculated frequently, and doing this for the whole collection would produce unacceptable performance. En mode virtuel, seuls les éléments requis sont calculés.In virtual mode, only the required items are calculated.

    Pour pouvoir utiliser le mode virtuel, vous devez gérer le RetrieveVirtualItem événement, qui est déclenché chaque fois que le ListView requiert un élément.In order to use virtual mode, you must handle the RetrieveVirtualItem event, which is raised every time the ListView requires an item. Ce gestionnaire d’événements doit créer le ListViewItem objet appartient à l’index spécifié.This event handler should create the ListViewItem object that belongs at the specified index. En outre, le VirtualListSize propriété doit être définie à la taille de la liste virtuelle.In addition, the VirtualListSize property must be set to the size of the virtual list.

    Gérer le SearchForVirtualItem événement vous permet de rechercher en mode virtuel.Handling the SearchForVirtualItem event enables searching in virtual mode. Si cet événement n’est pas géré, le FindItemWithText et FindNearestItem méthodes retourneront null.If this event is not handled, the FindItemWithText and FindNearestItem methods will return null.

    Vous pouvez gérer le CacheVirtualItems événement afin de maintenir un cache de ListViewItem objets.You can handle the CacheVirtualItems event in order to maintain a cache of ListViewItem objects. Si le calcul ou la recherche pour créer un ListViewItem objet est coûteux, le maintien d’un cache peut améliorer les performances.If the calculation or lookup to create a ListViewItem object is expensive, maintaining a cache can improve performance.

    Si le View propriété est définie sur Tile, la valeur sera automatiquement remplacée par LargeIcon lorsque VirtualMode est défini sur true.If the View property is set to Tile, the value will automatically be changed to LargeIcon when VirtualMode is set to true.

    En mode virtuel, le Items collecte est désactivée.In virtual mode, the Items collection is disabled. Tente d’y accéder entraîne une InvalidOperationException.Attempting to access it results in an InvalidOperationException. Est de même de la CheckedItems collection et le SelectedItems collection.The same is true of the CheckedItems collection and the SelectedItems collection. Si vous souhaitez récupérer les éléments sélectionnés ou activés, utilisez le SelectedIndices et CheckedIndices collections à la place.If you want to retrieve the selected or checked items, use the SelectedIndices and CheckedIndices collections instead.

    S’applique à