弹性包裹面板打破滚动查看器并且与其他人不兼容

时间:2014-04-25 13:42:46

标签: c# wpf xaml wrappanel

我有一个弹性包装面板,效果很好,正是我想要的。它允许我有两列“Stretched”控件,如果res足够小,它将换行到一列。现在它给我的问题是它打破了我的滚动查看器。当它进入一列时,scrollviewer不起作用,并且它在带有其他正常控件的stackpanel内不起作用。我不确定这里的解决方案是什么,但我知道继承'Panel'会导致这个问题。

public class ElasticWrapPanel : Panel
{
    /// <summary>
    /// Identifies the <see cref="DesiredColumnWidth"/> dependency property. 
    /// </summary>
    internal static readonly DependencyProperty DesiredColumnWidthProperty = DependencyProperty.Register("DesiredColumnWidth", typeof(double), typeof(ElasticWrapPanel), new PropertyMetadata(100d, new PropertyChangedCallback(OnDesiredColumnWidthChanged)));

    private int _columns;

    protected override Size MeasureOverride(Size availableSize)
    {
        _columns = (int)(availableSize.Width / DesiredColumnWidth);

        if (_columns > 2)
        {
            _columns = 2;
        }

        foreach (UIElement item in this.Children)
        {
            item.Measure(availableSize);
        }

        return base.MeasureOverride(availableSize);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        if (_columns != 0)
        {
            double columnWidth = Math.Floor(finalSize.Width / _columns);

            double top = 0;
            double rowHeight = 0;
            int column = 0;
            foreach (UIElement item in this.Children)
            {
                item.Arrange(new Rect(columnWidth * column, top, columnWidth, item.DesiredSize.Height));
                column++;
                rowHeight = Math.Max(rowHeight, item.DesiredSize.Height);

                if (column == _columns)
                {
                    column = 0;
                    top += rowHeight;
                    rowHeight = 0;
                }
            }
        }

        return base.ArrangeOverride(finalSize);
    }

    private static void OnDesiredColumnWidthChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var panel = (ElasticWrapPanel)obj;
        panel.InvalidateMeasure();
        panel.InvalidateArrange();
    }

    public double DesiredColumnWidth
    {
        get
        {
            return (double)GetValue(DesiredColumnWidthProperty);
        }

        set
        {
            SetValue(DesiredColumnWidthProperty, value);
        }
    }
}

XAML:

 <ScrollViewer>

    <StackPanel>

      <lib:ElasticWrapPanel DesiredColumnWidth="370" />

      <Button width="200" height="70" HorizontalAlignment="Center" />

    </StackPanel>

 </ScrollViewer>

问题:按钮没有堆叠,只是放在面板顶部。当包装面板转到一列控件而不是2时,滚动查看器不会启用。它就像它不能识别它周围的任何东西。谢谢你的任何建议。

0 个答案:

没有答案