Is there a WPF “WrapGrid” control available or an easy way to create one?

こ雲淡風輕ζ 提交于 2019-12-05 23:26:16

When I read your question I assumed you wanted something like this:

public class UniformWrapPanel : WrapPanel
{
  protected override Size MeasureOverride(Size constraint)
  {
    if(Orientation == Orientation.Horizontal)
      ItemWidth = Children.Select(element =>
        {
          element.Measure(constraint);
          return element.DesiredWidth;
        }).Max();
    else
      ... same for vertical ...

    return base.MeasureOverride(constraint);
  }
}

but I see someone else has already implemented a "UniformWrapPanel" and from your comments you indicate this is not what you were looking for.

The comment I don't understand is:

I want it to not force items to be a given size, but use their already existing size and therefore determine column widths automatically

Can you please provide an example to illustrate how you want things laid out with varying sizes? A picture might be nice. You also mention "tabstop" but don't give any definition of what that would be.

Here is some code that I whipped up based on some of the other controls that are close. It does a decent job of doing the layout, although it has an issue where grand-child controls do not fill up all their available space.

  protected override Size ArrangeOverride(Size finalSize)
    {
        double rowY = 0;
        int col = 0;
        double currentRowHeight = 0;


        foreach (UIElement child in Children)
        {
            var initialSize = child.DesiredSize;
            int colspan  = (int) Math.Ceiling(initialSize.Width/ ColumnSize);
            Console.WriteLine(colspan);
             double width = colspan * ColumnSize;



            if (col > 0 && (col * ColumnSize) + width > constrainedSize.Width)
            {
                rowY += currentRowHeight;
                col = 0;
                currentRowHeight = 0;
            }


            var childRect = new Rect(col * ColumnSize, rowY, width, initialSize.Height);
            child.Arrange(childRect);
            currentRowHeight = Math.Max(currentRowHeight, initialSize.Height);
            col+=colspan;
        }

        return finalSize;
    }

    Size constrainedSize;

    protected override Size MeasureOverride(Size constraint)
    {
        constrainedSize = constraint;
        return base.MeasureOverride(constraint);
    }

Try setting ItemWidth (or ItemHeight) property of the WrapPanel:

   <WrapPanel ItemWidth="48">
    <TextBlock Text="H" Background="Red"/>
    <TextBlock Text="e" Background="Orange"/>
    <TextBlock Text="l" Background="Yellow"/>
    <TextBlock Text="l" Background="Green"/>
    <TextBlock Text="o" Background="Blue"/>
    <TextBlock Text="!" Background="Violet"/>
   </WrapPanel>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!