Blazor | ComponentOne
Controls / ListView / Data Binding / Virtualization
In This Topic
    Virtualization
    In This Topic

    Besides on-demand loading, Virtualization is another factor to improve the performance of ListView while loading large amount of data. It fetches the items as the user scrolls. This data virtualization technique is supported in ListView through C1DataCollection which provides C1VirtualDataCollection class for data virtualized collection views. 

    In the following example, this class is used to create a custom data virtualized collection view that can be consumed for data virtualization in the ListView control.

    For virtualization in ListView, perform the following steps:

    1. In the Solution Explorer, right click the project name and select Add | New Folder and name it Models.
    2. Right click Models folder and select Add | Class. The Add New Item dialog appears.
    3. In the Add New Item dialog, set the name of the class, say Customer, and then click Add.
    4. Add the following code to the Customer class. In the following example, we are using Customer class to represent data in the ListView control.
      C#
      Copy Code
      public class Customer
      {
         int _id, _countryId;
         string _name, _email, _city;
         DateTime _OrderDate;
         double _orderTotal;
      
         static Random _rnd = new Random();
         static string[] _firstNames = 
            "Andy|Ben|Charlie|Dan|Ed|Fred|Herb|Jack|Mark|Ted".Split('|');
         static string[] _lastNames = 
            "Ambers|Bishop|Cole|Danson|Evers|Frommer|Heath|Myers|Richards|Stevens".Split('|');
         static string[] _emailServers = "gmail|yahoo|outlook|aol".Split('|');
         static string countries = 
            "China-Beijing,Shanghai|India-Delhi,Kolkata|United States-Washington,New York|Russia-Moscow,Saint Petersburg|Japan-Tokio,Yokohama";
         static KeyValuePair<string, string[]>[] _countries = 
            countries.Split('|').Select(str => new KeyValuePair<string, string[]>(str.Split('-').First(), 
                str.Split('-').Skip(1).First().Split(','))).ToArray();
            
              
         public Customer()
         {
         }
      
         public Customer(int id)
         {
            ID = id;
            Name = GetName();
            Email = string.Format("{0}@{1}.com", (Name.Substring(0, 3)).ToLower(), GetString(_emailServers));
            CountryId = _rnd.Next() % _countries.Length;
            var cities = _countries[CountryId].Value;
            City = GetString(cities);
            OrderDate = DateTime.Today.AddDays(-_rnd.Next(1, 365)).AddHours(_rnd.Next(0, 24)).AddMinutes(_rnd.Next(0, 60));
            OrderTotal = Math.Round(_rnd.NextDouble() * 10000.00, 2);
         }
      
         public int ID
         {
            get { return _id; }
            set
            {
                if (value != _id)
                {
                    _id = value;
                }
            }
         }
         public string Name
         {
            get { return _name; }
            set
            {
                if (value != _name)
                {
                    _name = value;
                }
            }
         }
         public string Email
         {
            get { return _email; }
            set
            {
                if (value != _email)
                {
                    _email = value;
                }
            }
         }
         public string City
         {
            get { return _city; }
            set
            {
                if (value != _city)
                {
                     _city = value;
                }
            }
         }
      
         public int CountryId
         {
            get { return _countryId; }
            set
            {
                if (value != _countryId && value > -1 && value < _countries.Length)
                {
                     _countryId = value;
                }
                  }
         }
         public DateTime OrderDate
         {
            get { return _OrderDate; }
            set
            {
                if (value != _OrderDate)
                {
                    _OrderDate = value;
                }
            }
         }
      
         public double OrderTotal
         {
            get { return _orderTotal; }
            set
            {
                if (value != _orderTotal)
                {
                     _orderTotal = value;
                }
            }
         }
      
         // ** utilities
         static string GetString(string[] arr)
         {
              return arr[_rnd.Next(arr.Length)];
         }
         static string GetName()
         {
              return string.Format("{0} {1}", GetString(_firstNames), GetString(_lastNames));
         }
         public string Country
         {
              get { return _countries[_countryId].Key; }
         }
      
         // ** static list provider
         public static ObservableCollection<Customer> GetCustomerList(int count)
         {
              var list = new ObservableCollection<Customer>();
              for (int i = 0; i < count; i++)
              {
                  list.Add(new Customer(i));
              }
              return list;
          }
      }
      
    5. Create a new class, say VirtualModeDataCollection, and add it to the Models folder. This class creates a virtualized data collection view for ListView.
      C#
      Copy Code
      public class VirtualModeDataCollection : C1VirtualDataCollection<Customer>
          {
              public int TotalCount { get; set; } = 1_000;
      
              protected override async Task<Tuple<int, IReadOnlyList<Customer>>> 
                      GetPageAsync(int pageIndex, int startingIndex, int count, 
                      IReadOnlyList<SortDescription> sortDescriptions = null, 
                      FilterExpression filterExpression = null, 
                      CancellationToken cancellationToken = default(CancellationToken))
              {
                  await Task.Delay(500, cancellationToken);//Simulates network traffic.
                  return new Tuple<int, IReadOnlyList<Customer>>(TotalCount, 
                                              Enumerable.Range(startingIndex, count).Select(i => new Customer(i)).ToList());
              }
          }
      
    6. Right click Pages folder, select Add | Razor page to add a new Razor page, say VirtualMode, and add the following code in the page for data virtualization.
      Razor
      Copy Code
      @using C1.Blazor.ListView
      
      <C1ListView ItemsSource="customers" T="Customer" Style="@("max-height:50vh")">
          <ItemTemplate Context="customer">
              @customer.Id - @customer.Name
          </ItemTemplate>
      </C1ListView>
      
      @code
      {
          VirtualModeDataCollection customers;
      
          protected override async Task OnInitializedAsync()
          {
              customers = new VirtualModeDataCollection();
              await customers.LoadAsync(0, 0);
          }
      }