问题
Essentially I want a wrapPanel, but I would like items to snap to a grid rather than be pressed up to the left, so I can get a nice uniform looking grid, that automatically consumes available space.
WrapPanel handles the resize part. WPF.Contrib.AutoGrid handles a nice automatic grid.
Anyone got a control that combines them?
My use case is I have a series of somewhat irregularly shaped controls. I would like them to appear in nice columns so the wrap panel should snap to the next "tabstop" when placing a control
回答1:
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.
回答2:
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);
}
回答3:
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>
来源:https://stackoverflow.com/questions/3009370/is-there-a-wpf-wrapgrid-control-available-or-an-easy-way-to-create-one