Set max rows in a wrap panel
Asked Answered
C

4

5

I need to configure a wrap panel where I can set the max rows or max columns in it.

This is really necessary, I'm using WPF 4.0. But the another day, I was programmin Metro applications and I remember that one of its controls has this properties, but in WPF not (until I know).

Is exists such control in WPF 4.0? Or do I need to create a new one?

Concert answered 24/7, 2012 at 17:45 Comment(2)
what should happen if an element is added and the max number of, say, row is reached, and we would need a new row to display this element ??Talich
Maybe you could use an UniformGrid? e.g. <UniformGrid Rows="10">Masha
N
5

You can set ItemHeight and ItemWidth properties to set the max rows and columns...

For more info, have a look here

Newcastle answered 24/7, 2012 at 17:54 Comment(0)
M
6

Here is an implementation of such a WrapPanel.

Xaml:

<loc:WrapPanelWithRowsOrColumnsCount
    xmlns:loc="clr-namespace:..."
    Orientation="Vertical"
    RowsOrColumnsCount="2">
    <TextBox Text="Andrew" Margin="2" Height="30" />
    <TextBox Text="Betty" Margin="2" Height="40" />
    <TextBox Text="Celine" Margin="2" Height="20" />
    <TextBox Text="Dick" Margin="2" Height="20" />
    <TextBox Text="Enron" Margin="2" Height="30" />
    <TextBox Text="Felix" Margin="2" Height="20" />
    <TextBox Text="Hanibal" Margin="2" Height="30" />
</loc:WrapPanelWithRowsOrColumnsCount>

Result:

enter image description here

Code of WrapPanelWithRowsOrColumnsCount.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

public class WrapPanelWithRowsOrColumnsCount : WrapPanel
{
    public static readonly DependencyProperty RowsOrColumnsCountProperty = 
        DependencyProperty.Register(
            "RowsOrColumnsCount",
            typeof(int),
            typeof(WrapPanelWithRowsOrColumnsCount),
            new PropertyMetadata(int.MaxValue));

    public int RowsOrColumnsCount
    {
        get { return (int)GetValue(RowsOrColumnsCountProperty); }
        set { SetValue(RowsOrColumnsCountProperty, Math.Max(value, 1)); }
    }

    protected override Size MeasureOverride(Size availableSize)
    {
        if (Children.Count > 0)
        {
            Size newAvailableSize;

            if (Orientation == Orientation.Horizontal)
            {
                var suitableWidth = EstimateSuitableRowOrColumnLength(Children.Cast<UIElement>(),
                                                                        true,
                                                                        availableSize,
                                                                        RowsOrColumnsCount);

                newAvailableSize = 
                    double.IsNaN(suitableWidth) || suitableWidth <= 0
                        ? availableSize 
                        : new Size(Math.Min(suitableWidth, availableSize.Width), availableSize.Height);
            }
            else
            {
                var suitableHeigth = EstimateSuitableRowOrColumnLength(Children.Cast<UIElement>(),
                                                                        false,
                                                                        availableSize,
                                                                        RowsOrColumnsCount);
                newAvailableSize =
                    double.IsNaN(suitableHeigth) || suitableHeigth <= 0
                        ? availableSize
                        : new Size(availableSize.Width, Math.Min(suitableHeigth, availableSize.Height));
            }

            return base.MeasureOverride(newAvailableSize);
        }
        else
        {
            return base.MeasureOverride(availableSize);
        }
    }

    private double EstimateSuitableRowOrColumnLength(IEnumerable<UIElement> elements,
                                                        bool trueRowsFalseColumns,
                                                        Size availableSize,
                                                        int rowsOrColumnsCount)
    {
        var elementsList = elements.ToList();

        var desiredLengths = elementsList.Select(el => DesiredLength(el, availableSize, trueRowsFalseColumns)).ToList();

        var maxLength = desiredLengths.Where(length => !double.IsNaN(length)).Concat(new[] { 0.0 }).Max();

        if (maxLength <= 0.0)
        {
            return double.NaN;
        }

        var desiredLengthsRepaired = desiredLengths.Select(length => double.IsNaN(length) ? maxLength : length).ToList();

        var totalDesiredLength = desiredLengthsRepaired.Sum();

        var maxCount = Math.Min(rowsOrColumnsCount, elementsList.Count);

        var suitableRowOrColumnLength = totalDesiredLength / maxCount;

        double nextLengthIncrement;

        while (CountRowsOrColumnsNumber(desiredLengthsRepaired, suitableRowOrColumnLength, out nextLengthIncrement) > maxCount)
        {
            suitableRowOrColumnLength += nextLengthIncrement;
        }

        suitableRowOrColumnLength = Math.Max(suitableRowOrColumnLength, desiredLengthsRepaired.Max());

        return suitableRowOrColumnLength;
    }

    private int CountRowsOrColumnsNumber(List<double> desiredLengths, double rowOrColumnLengthLimit, out double nextLengthIncrement)
    {
        int rowOrColumnCount = 1;
        double currentCumulativeLength = 0;
        bool nextNewRowOrColumn = false;

        var minimalIncrement = double.MaxValue;

        foreach (var desiredLength in desiredLengths)
        {
            if (nextNewRowOrColumn)
            {
                rowOrColumnCount++;
                currentCumulativeLength = 0;
                nextNewRowOrColumn = false;
            }

            if (currentCumulativeLength + desiredLength > rowOrColumnLengthLimit)
            {
                minimalIncrement = Math.Min(minimalIncrement,
                                            currentCumulativeLength + desiredLength - rowOrColumnLengthLimit);

                if (currentCumulativeLength == 0)
                {
                    nextNewRowOrColumn = true;
                    currentCumulativeLength = 0;
                }
                else
                {
                    rowOrColumnCount++;
                    currentCumulativeLength = desiredLength;
                }
            }
            else
            {
                currentCumulativeLength += desiredLength;
            }
        }

        nextLengthIncrement = minimalIncrement != double.MaxValue ? minimalIncrement : 1;

        return rowOrColumnCount;
    }

    private double DesiredLength(UIElement el, Size availableSize, bool trueRowsFalseColumns)
    {
        el.Measure(availableSize);
        Size next = el.DesiredSize;

        var length = trueRowsFalseColumns ? next.Width : next.Height;

        if (Double.IsInfinity(length) ||
            Double.IsNaN(length))
        {
            return Double.NaN;
        }
        else
        {
            return length;
        }
    }
}

The solution was inspired by this codeproject article.

Maharanee answered 31/1, 2017 at 9:10 Comment(1)
I copied the code but it takes also no effect on items in wrap panel like @nikotromus already recognizedSpotty
N
5

You can set ItemHeight and ItemWidth properties to set the max rows and columns...

For more info, have a look here

Newcastle answered 24/7, 2012 at 17:54 Comment(0)
D
0

I think for what you are trying to accomplish the WPF Grid is the better solution. By setting a specific count of grid rows you can simulate that behaviour of a wrap panel and it is more flexibel.

<Grid>
  <Grid.ColumnDefinitions>
    <ColumDefinition Height="Auto"/>
    <ColumDefinition Height="Auto"/>
    <ColumDefinition Height="Auto"/>
    .... 
    <ColumDefinition Height="*/>  
  </Grid.ColumnDefinitions>
<Grid>
Decker answered 24/7, 2012 at 17:52 Comment(0)
M
0

The only way I can think you could do this with the WrapPanel is if you know the size of the objects (and they're consistent), so you could set the height/width of the WrapPanel accordingly. That's pretty ugly though.

One thing to think about: What do you want the panel to do with the elements beyond that maximum number of rows/columns? Or is there always the right number of elements? If that's the case, then you should really look at the Grid instead.

Mutule answered 24/7, 2012 at 17:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.