Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jonstodle
Last active April 13, 2019 21:48
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonstodle/ff4621c4e78ecebe1466 to your computer and use it in GitHub Desktop.
Save jonstodle/ff4621c4e78ecebe1466 to your computer and use it in GitHub Desktop.
A panel which arranges it's children into the specified amount of columns and stretches them to uniformly consume the whole width
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace KodeFisk
{
public class UniformWidthWrapPanel : Panel
{
public UniformWidthWrapPanel()
{
MaximumColumns = 1;
}
public int MaximumColumns
{
get { return (int)GetValue(MaximumColumnsProperty); }
set { SetValue(MaximumColumnsProperty, value); }
}
// Using a DependencyProperty as the backing store for MaximumColumns. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MaximumColumnsProperty =
DependencyProperty.Register("MaximumColumns", typeof(int), typeof(UniformWidthWrapPanel), new PropertyMetadata(null));
protected override Size MeasureOverride(Size availableSize)
{
var finalSize = new Size { Width = availableSize.Width };
var columnWidth = availableSize.Width / MaximumColumns;
var rowHeight = 0d;
var rowChildCount = 0;
foreach (var child in Children)
{
child.Measure(new Size(columnWidth, availableSize.Height));
if (rowChildCount < MaximumColumns)
{
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 columnWidth = finalSize.Width / MaximumColumns;
var posY = 0d;
var rowHeight = 0d;
var rowChildCount = 0;
foreach (var child in Children)
{
if (rowChildCount >= MaximumColumns)
{
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;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment