Skip to content

Instantly share code, notes, and snippets.

@jonstodle
Last active April 15, 2022 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonstodle/24f508591066521acbae to your computer and use it in GitHub Desktop.
Save jonstodle/24f508591066521acbae to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace KodeFisk.Panels
{
class UniformMinWidthWrapPanel : Panel
{
public UniformMinWidthWrapPanel()
{
MinColumnWidth = 200;
}
public double MinColumnWidth
{
get { return (double)GetValue(MinColumnWidthProperty); }
set { SetValue(MinColumnWidthProperty, value); }
}
// Using a DependencyProperty as the backing store for MinColumnWidth. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MinColumnWidthProperty =
DependencyProperty.Register(nameof(MinColumnWidth), typeof(double), typeof(UniformMinWidthWrapPanel), new PropertyMetadata(null));
protected override Size MeasureOverride(Size availableSize)
{
var finalSize = new Size { Width = availableSize.Width };
var columns = Math.Floor(finalSize.Width / MinColumnWidth);
var columnWidth = availableSize.Width / columns;
var rowHeight = 0d;
var rowChildCount = 0;
foreach (var child in Children)
{
child.Measure(new Size(columnWidth, availableSize.Height));
if (rowChildCount < columns)
{
rowHeight = Math.Max(child.DesiredSize.Height, rowHeight);
}
else
{
finalSize.Height += rowHeight;
rowHeight = child.DesiredSize.Height;
rowChildCount = 0;
}
rowChildCount++;
}
finalSize.Height += rowHeight;
return finalSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
var columns = Math.Floor(Math.Max(finalSize.Width, MinColumnWidth) / MinColumnWidth);
var columnWidth = finalSize.Width / columns;
var posY = 0d;
var rowHeight = 0d;
var rowChildCount = 0;
foreach (var child in Children)
{
if (rowChildCount >= columns)
{
rowChildCount = 0;
posY += rowHeight;
rowHeight = 0;
}
child.Arrange(new Rect(columnWidth * rowChildCount, posY, columnWidth, child.DesiredSize.Height));
rowHeight = Math.Max(child.DesiredSize.Height, rowHeight);
rowChildCount++;
}
return finalSize;
}
}
}
@CodingOctocat
Copy link

great code, but some item overflow. why?

669887aded775c9afdd3aa188cc36ce

@jonstodle
Copy link
Author

I haven't looked at this code in near a decade, but it looks correct from what I remember. I haven't done XAML in a while either, but my first instinct would be to check whether there is some conflicting constraint on the item; maybe a minsize of some sort that overrides the column width restriction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment