Nested Scroll Areas

2020-01-31 02:48发布

I creating a control for WPF, and I have a question for you WPF gurus out there.

I want my control to be able to expand to fit a resizable window.

In my control, I have a list box that I want to expand with the window. I also have other controls around the list box (buttons, text, etc).

I want to be able to set a minimum size on my control, but I want the window to be able to be sized smaller by creating scroll bars for viewing the control.

This creates nested scroll areas: One for the list box and a ScrollViewer wrapping the whole control.

Now, if the list box is set to auto size, it will never have a scroll bar because it is always drawn full size within the ScrollViewer.

I only want the control to scroll if the content can't get any smaller, otherwise I don't want to scroll the control; instead I want to scroll the list box inside the control.

How can I alter the default behavior of the ScrollViewer class? I tried inheriting from the ScrollViewer class and overriding the MeasureOverride and ArrangeOverride classes, but I couldn't figure out how to measure and arrange the child properly. It appears that the arrange has to affect the ScrollContentPresenter somehow, not the actual content child.

Any help/suggestions would be much appreciated.

7条回答
淡お忘
2楼-- · 2020-01-31 03:15

I've created a class to work around this problem:

public class RestrictDesiredSize : Decorator
{
    Size lastArrangeSize = new Size(double.PositiveInfinity, double.PositiveInfinity);

    protected override Size MeasureOverride(Size constraint)
    {
        Debug.WriteLine("Measure: " + constraint);
        base.MeasureOverride(new Size(Math.Min(lastArrangeSize.Width, constraint.Width),
                                      Math.Min(lastArrangeSize.Height, constraint.Height)));
        return new Size(0, 0);
    }

    protected override Size ArrangeOverride(Size arrangeSize)
    {
        Debug.WriteLine("Arrange: " + arrangeSize);
        if (lastArrangeSize != arrangeSize) {
            lastArrangeSize = arrangeSize;
            base.MeasureOverride(arrangeSize);
        }
        return base.ArrangeOverride(arrangeSize);
    }
}

It will always return a desired size of (0,0), even if the containing element wants to be bigger. Usage:

<local:RestrictDesiredSize MinWidth="200" MinHeight="200">
     <ListBox />
</local>
查看更多
登录 后发表回答