Creating a custom VirtualizingLayout for Avalonia.ItemsRepeater

My overall goal is to have a grid layout with a variable number columns depending on a set of screen size breakpoints to display a list of controls. I.e., with a width of 720px, there would be 4 columns, with a width of 1024px there would be 5, etc..

From what I’ve found, this isn’t necessarily natively supported with default Avalonia controls, so I’ve gone about creating my own layout class to use as a AttachedLayout to an ItemsRepeater, building on the idea of a UniformGridLayout.

I have the basics of the class down, and it works as I’d like with regards to layout, but am having some issues implementing virtualization. Without virtualization, the performance absolutely tanks as you’d expect, so this is a must have.

For reference, here is the class as I have it now

public class BreakpointColumnGridLayout : VirtualizingLayout
{
    public static readonly StyledProperty<List<(double width, int columns)>> BreakpointsProperty =
        AvaloniaProperty.Register<BreakpointColumnGridLayout, List<(double width, int columns)>>(nameof(Breakpoints), defaultValue: new List<(double width, int columns)>
        {
            (1058, 4),
            (1314, 5),
            (int.MaxValue, 6),
        });

    public static readonly StyledProperty<double> GutterSizeProperty =
        AvaloniaProperty.Register<BreakpointColumnGridLayout, double>(nameof(GutterSize), defaultValue: 10.0);

    public static readonly StyledProperty<bool> LimitToOneRowProperty =
        AvaloniaProperty.Register<BreakpointColumnGridLayout, bool>(nameof(LimitToOneRow), defaultValue: false);

    public bool LimitToOneRow
    {
        get => GetValue(LimitToOneRowProperty);
        set => SetValue(LimitToOneRowProperty, value);
    }

    public List<(double width, int columns)> Breakpoints
    {
        get => GetValue(BreakpointsProperty);
        set => SetValue(BreakpointsProperty, value);
    }

    public double GutterSize
    {
        get => GetValue(GutterSizeProperty);
        set => SetValue(GutterSizeProperty, value);
    }

    protected override Size MeasureOverride(VirtualizingLayoutContext context, Size availableSize)
    {
        if (context.ItemCount <= 0 || Breakpoints == null || !Breakpoints.Any())
        {
            return new Size(0, 0);
        }

        var columns = DetermineColumns(availableSize.Width);
        var itemWidth = CalculateItemWidth(availableSize.Width, columns, GutterSize);
        itemWidth = Math.Max(itemWidth, 10);

        var itemCount = LimitToOneRow ? Math.Min(context.ItemCount, columns) : context.ItemCount;
        for (var i = 0; i < itemCount; i++)
        {
            var child = context.GetOrCreateElementAt(i, ElementRealizationOptions.None);
            child.Measure(new Size(itemWidth, availableSize.Height));
        }

        var itemHeight = itemCount > 0 ? context.GetOrCreateElementAt(0).DesiredSize.Height : 0;
        var totalHeight = LimitToOneRow ? itemHeight : ((Math.Ceiling((double)itemCount / columns) * itemHeight) + ((Math.Ceiling((double)itemCount / columns) - 1) * GutterSize));

        totalHeight = Math.Max(totalHeight, 0);
        var totalWidth = Math.Max(availableSize.Width, 0);

        return new Size(totalWidth, totalHeight);
    }

    protected override Size ArrangeOverride(VirtualizingLayoutContext context, Size finalSize)
    {
        if (context.ItemCount <= 0 || Breakpoints == null || !Breakpoints.Any())
        {
            return finalSize;
        }

        var columns = DetermineColumns(finalSize.Width);
        var itemWidth = CalculateItemWidth(finalSize.Width, columns, GutterSize);
        itemWidth = Math.Max(itemWidth, 10);

        var x = 0.0;
        var y = 0.0;
        var totalHeight = 0.0;
        var maxHeightInARow = 0.0;

        var itemCount = LimitToOneRow ? Math.Min(context.ItemCount, columns) : context.ItemCount;
        for (var i = 0; i < itemCount; i++)
        {
            var child = context.GetOrCreateElementAt(i, ElementRealizationOptions.None);
            var childSize = child.DesiredSize;

            if (!LimitToOneRow && i % columns == 0 && i != 0)
            {
                x = 0;
                y += maxHeightInARow + GutterSize;
                totalHeight += maxHeightInARow + GutterSize;
                maxHeightInARow = 0;
            }

            child.Arrange(new Rect(x, y, itemWidth, childSize.Height));
            x += itemWidth + GutterSize;
            maxHeightInARow = Math.Max(maxHeightInARow, childSize.Height);

            if (i == itemCount - 1 || LimitToOneRow)
            {
                totalHeight += maxHeightInARow;
            }
        }

        return new Size(finalSize.Width, totalHeight);
    }

    private int DetermineColumns(double containerWidth)
    {
        if (Breakpoints == null || !Breakpoints.Any())
        {
            return 0;
        }

        var sortedBreakpoints = Breakpoints.OrderBy(b => b.width).ToList();
        foreach (var breakpoint in sortedBreakpoints)
        {
            if (containerWidth <= breakpoint.width)
            {
                return breakpoint.columns;
            }
        }

        return sortedBreakpoints.Last().columns;
    }

    private double CalculateItemWidth(double containerWidth, int columns, double gutterSize)
    {
        if (columns <= 0)
        {
            return 0;
        }

        var totalGutterWidth = (columns - 1) * gutterSize;
        var itemWidth = Math.Floor((containerWidth - totalGutterWidth) / columns);
        return itemWidth;
    }
}

The class inherits from VirtualizingLayout, but does not actually do any kind of virtualization. I’ve tried a few things with context.RealizationRect, but I don’t think I have a full grasp on how it should be used in MeasureOverride and ArrangeOverride. I had something along the lines of this in ArrangeOverride:

if (x >= realizationBounds.Left && x <= realizationBounds.Right &&
                y >= realizationBounds.Top && y <= realizationBounds.Bottom)
            {
                child.Arrange(new Rect(x, y, itemWidth, childSize.Height));
            }
            else if (y > realizationBounds.Bottom)
            {
                break;
            }

This had a set of issues:

  1. It would did not render the last row correctly.
  2. Fast strolling on large datasets would draw nothing at all until the user scrolled back to top.
  3. It required the ItemsRepeater to need VerticalAlignment=Top, not sure on why that was.

I’m looking for a little help getting pointed in the right direction here.

New contributor

Lambhouse is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật