ListView.VirtualMode 속성

정의

사용자가 직접 ListView 컨트롤에 대한 데이터 관리 작업을 제공했는지 여부를 나타내는 값을 가져오거나 설정합니다.

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

속성 값

ListView에서 사용자가 제공하는 데이터 관리 작업을 사용하면 true이고, 그렇지 않으면 false입니다. 기본값은 false입니다.

예외

VirtualModetrue로 설정되어 있고 다음 조건 중 하나에 해당하는 경우

예제

이 예제에서는 내용이 처음 1만 제곱인 간단한 ListView 을 보여 줍니다. 검색을 처리하고 성능 향상을 위해 캐시를 사용합니다.

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

설명

속성을 로 VirtualMode 설정하면 true 가 가상 모드로 전환됩니다 ListView . 가상 모드에서 일반 Items 컬렉션은 사용되지 않습니다. 대신 개체 ListViewItem 는 필요에 따라 동적으로 ListView 만들어집니다.

가상 모드는 여러 상황에서 유용할 수 있습니다. 이미 메모리에 ListView 있는 매우 큰 컬렉션에서 개체를 채워야 하는 경우 각 항목에 대한 개체를 ListViewItem 만드는 것은 낭비될 수 있습니다. 가상 모드에서는 필요한 항목만 생성됩니다. 다른 경우에는 개체의 ListViewItem 값을 자주 다시 계산해야 할 수 있으며 전체 컬렉션에 대해 이 작업을 수행하면 허용할 수 없는 성능이 생성됩니다. 가상 모드에서는 필요한 항목만 계산됩니다.

가상 모드를 사용하려면 에 항목이 RetrieveVirtualItem 필요할 때마다 ListView 발생하는 이벤트를 처리해야 합니다. 이 이벤트 처리기는 지정된 인덱스에 속하는 개체를 만들어야 ListViewItem 합니다. 또한 VirtualListSize 속성을 가상 목록의 크기로 설정해야 합니다.

이벤트를 처리하면 SearchForVirtualItem 가상 모드에서 검색할 수 있습니다. 이 이벤트가 처리되지 않으면 및 FindNearestItem 메서드는 FindItemWithText 를 반환null합니다.

개체의 캐시 ListViewItemCacheVirtualItems 유지하기 위해 이벤트를 처리할 수 있습니다. 개체를 만들기 ListViewItem 위한 계산 또는 조회 비용이 많이 드는 경우 캐시를 유지 관리하면 성능이 향상될 수 있습니다.

속성이 로 View 설정된 Tile경우 값은 가 로 설정된 true경우 VirtualMode 로 자동으로 변경 LargeIcon 됩니다.

가상 모드에서 컬렉션은 Items 사용하지 않도록 설정됩니다. 액세스를 시도하면 가 발생합니다 InvalidOperationException. 컬렉션과 SelectedItems 컬렉션의 CheckedItems 경우도 마찬가지입니다. 선택하거나 선택한 항목을 검색하려면 및 CheckedIndices 컬렉션을 대신 사용합니다SelectedIndices.

적용 대상