これは、私が望んでいた機能を得るために私がしなければならなかったことです。まず、SquareWrapPanel を作成する必要があります。ここで魔法が起こり、アイテムを思いどおりに配置できます。
protected override Size ArrangeOverride(Size finalSize)
{
return ArrangeByChildCount(finalSize);
}
private Size ArrangeByChildCount(Size finalSize)
{
double childWidth = 0;
double childHeight = 0;
foreach (UIElement e in Children)
{
e.Measure(finalSize);
childWidth = e.DesiredSize.Width;
childHeight = e.DesiredSize.Height;
}
if (Children.Count > 0)
{
int square = (int)Math.Sqrt(Children.Count);
int rowCount = square + Children.Count % square;
int columnCount = square;
double height = rowCount * childHeight;
double width = columnCount * childWidth;
Size size = new Size(width, height);
base.ArrangeOverride(size);
return size;
}
else
{
return new Size(300, 300);
}
}
次に、ItemsControl を拡張したカスタム パネルを作成しました。そうすれば、アイテムのコレクションをそれにバインドできます。コードビハインドには何もありませんが、これが私が使用しなければならなかったスタイルです。
<Style TargetType="{x:Type local:SquareItemsPanel}" BasedOn="{StaticResource {x:Type ItemsControl}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ItemsControl">
<Border BorderBrush="Black" BorderThickness="2" CornerRadius="4">
<Expander x:Name="exp" Header="View">
<local:SquareWrapPanel IsItemsHost="True"/>
</Expander>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>