asp.net-coreblazorcomponents

Interact with the Virtualize component


I am currently designing a website using Blazor WebAssembly. I have a list that I want to display using the Virtualize component. For basic usage, I found the needed documentation online.

However, I'd like to know if there's a way to programmatically navigate to a specific item in the list—for example, jump directly to the 50th element—and display the range from the 50th to the 60th.

In other words:

Can I interact with the Virtualize component to control which rows are displayed? Is it possible to achieve this without using JavaScript?


Solution

  • Blazor only achieve scroll actions by javascript so there's no way to scroll to that part.
    But if your demand is to control which rows are displayed and willing to sacrifice some convinience, you could change the Item Source directly.

    @page "/"
    <button @onclick="()=>{JumpToRow(50,10);}">Go to Row 50-60</button>
    <button @onclick="Reset">Reset</button>
    <Virtualize ItemsProvider="LoadItems" ItemSize="50" @ref="virtualizeRef" >
        <ItemContent>
            <p>@context</p>
        </ItemContent>
    </Virtualize>
    @code {
        private List<string> items = Enumerable.Range(1, 1000).Select(i => $"Item {i}").ToList();
        private int StartIndex = 0;
        private int CustomCount= 0;
        private Virtualize<string> virtualizeRef;
    
        private ValueTask<ItemsProviderResult<string>> LoadItems(ItemsProviderRequest request)
        {
            var start = StartIndex > 0 ? StartIndex : request.StartIndex;
            var count = CustomCount > 0 ? CustomCount : request.Count;
    
            var result = items.Skip(start).Take(count).ToList();
            return ValueTask.FromResult(new ItemsProviderResult<string>(result, items.Count));
        }
    
        private void JumpToRow(int startIndex,int customCount)
        {
            StartIndex = startIndex;
            CustomCount = customCount;
            virtualizeRef.RefreshDataAsync(); // Forces the component to refresh the data set
        }
    
        private void Reset()
        {
            StartIndex = 0;
            CustomCount = 0;
            virtualizeRef.RefreshDataAsync();
        }
    }