List Items Vertically on a WrapPanel and take advantage of multiple columns

前端 未结 5 1046
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 16:21

I need to list items (all of same size) vertically (with a ScrollViewer). I want the items to spread through x columns if the container is large enough to display

5条回答
  •  不思量自难忘°
    2021-01-01 16:47

    Finally got something that works but it needs code. I agree with all of you when you say that we need to resize height of the WrapPanel to make that works. Here is my solution :

    
        
            

    Here is the CodeBehind :

    private void ScrollViewer_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        // Stupid magical number because ViewPortHeight is sometimes not accurate
        Double MAGICALNUMBER = 2;
    
        // Ensure ViewPortSize is not 0
        if (scroll1.ViewportWidth <= MAGICALNUMBER || scroll1.ViewportHeight <= MAGICALNUMBER)
            return;
    
        Size contentSize = new Size(scroll1.ViewportWidth - MAGICALNUMBER, scroll1.ViewportHeight - MAGICALNUMBER);
        Size itemSize = new Size(wp1.ItemWidth, wp1.ItemHeight);
    
        Size newSize = CalculateSizeBasedOnContent(contentSize, wp1.Children.Count, itemSize);
    
        wp1.Width = newSize.Width;
        wp1.Height = newSize.Height;
    }
    
    
    private Size CalculateSizeBasedOnContent(Size containerSize, int itemsCount, Size itemSize)
    {
    
        int iPossibleColumns = (int)Math.Floor(containerSize.Width / itemSize.Width);
        int iPossibleRows = (int)Math.Floor(containerSize.Height / itemSize.Height);
    
        // If all items can fit in first column without scrolling (or if container is narrow than the itemWidth)
        if (itemsCount <= iPossibleRows || containerSize.Width < itemSize.Width)
        return new Size(itemSize.Width, (itemsCount * itemSize.Height));
    
        // If all items can fit in columns without scrollbar
        if (iPossibleColumns * iPossibleRows > itemsCount)
        {
        int columnsNeededForDisplay = (int)Math.Ceiling((itemsCount/(Double) iPossibleRows));
        return new Size(columnsNeededForDisplay * itemSize.Width, containerSize.Height);
        }
    
        // Here scrolling is needed even after spreading in columns
        int itemsPerColumn = (int)Math.Ceiling(wp1.Children.Count / (Double)iPossibleColumns);
        return new Size(containerSize.Width, itemsPerColumn * itemSize.Height);
    
    }
    

提交回复
热议问题