例如,实现一个TwoColumnStackPanel. 顾名思义,一般StackPanel只能将元素堆叠在一列,而我的 TwoColumnStackPanel 可以将元素堆叠在两列。
TwoColumnStackPanel 应在两列中均匀分布元素。如果是4个元素,左边2个右边2个;5 个元素,左 2 和右 3。
我认为 TwoColumnStackPanel 实际上是两个并排的 StackPanel,它可以使用现有的 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;
    }
}
上面的代码在标签行抛出异常。如何解决?我是否以正确的方式实施它?