For example, implement a TwoColumnStackPanel
. As the name suggests, the general StackPanel
can only stack elements in one column, while my TwoColumnStackPanel can stack elements in two columns.
The TwoColumnStackPanel should distribute elements evenly in the two columns. If 4 elements, the left 2 and the right 2; 5 elements, the left 2 and right 3.
I think the TwoColumnStackPanel is actually two side-by-side StackPanels and can it be implemented using the existing StackPanel?
class TwoColumnStackPanel : Panel
{
private readonly StackPanel leftPanel;
private readonly StackPanel rightPanel;
public TwoColumnStackPanel()
{
leftPanel = new StackPanel();
rightPanel = new StackPanel();
}
protected override Size MeasureOverride(Size availableSize)
{
int size = InternalChildren.Count;
int leftCount = size / 2;
int rightCount = size - leftCount;
//Load elements to left stackpanel.
int index = 0;
leftPanel.Children.Clear();
for (int s = 0; s < leftCount; s++)
{
leftPanel.Children.Add(InternalChildren[index + s]);
}
//Load elements to right stackpanel.
index += leftCount;
rightPanel.Children.Clear();
for (int s = 0; s < rightCount; s++)
{
rightPanel.Children.Add(InternalChildren[index + s]);//error
}
//Measure the two stackpanel and the sum is my desired size.
double columnWidth = availableSize.Width / 2;
leftPanel.Measure(new Size(columnWidth, availableSize.Height));
rightPanel.Measure(new Size(columnWidth, availableSize.Height));
return new Size(leftPanel.DesiredSize.Width + rightPanel.DesiredSize.Width, Math.Max(leftPanel.DesiredSize.Height, rightPanel.DesiredSize.Height));
}
protected override Size ArrangeOverride(Size finalSize)
{
leftPanel.Arrange(new Rect(0,0,leftPanel.DesiredSize.Width,leftPanel.DesiredSize.Height));
rightPanel.Arrange(new Rect(leftPanel.DesiredSize.Width,0,rightPanel.DesiredSize.Width,rightPanel.DesiredSize.Height));
return finalSize;
}
}
The above code throws exception at the label line. How to fix it? Am I implementing it in the right way?