滚动条位置正在移动可见/不可见的更改控件

时间:2010-12-14 17:25:10

标签: c# controls scrollbar

我有一个带有可滚动面板的表单和两个坐在彼此顶部的控件 - 一个不可见。基于某个条件激活该表单时,我可能会交换两个控件的可见属性。这些控件位于可滚动面板的底部。如果当我离开该表单时,我将其保持滚动到底部,更改条件将导致控件的可见性交换并返回到该表单,可见控件将在页面下降约200px,留下大的间隙。有人知道是什么原因引起的吗?我尝试在表单关闭时将滚动条位置重置到顶部,但这只会导致较小的间隙,有时控件会更高地移动到其他控件中。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

以下是再现问题的示例。如果鼠标移动到红色标签上,则button2的可见性将更改为true,这会导致滚动跳回到Button1。

public class Form123456 : Form {

    public Form123456() {
        Controls.Add(new UC1());
    }

    public class UC1 : UserControl {
        Button b1 = new Button { Text = "Button1" };
        Label lb = new Label { Text = "_", AutoSize = true, BackColor = Color.Red };
        Button b2 = new Button { Text = "Button2", Visible = false };
        Button b2b = new Button { Text = "x" };
        Button b3 = new Button { Text = "Button3" };
        public UC1() {
            AutoScroll = true;
            Dock = DockStyle.Fill;
            b1.Location = new Point(0, 200);
            b2.Location = new Point(0, 600);
            lb.Location = new Point(70, 600);
            b2b.Location = new Point(90, 600);
            b3.Location = new Point(0, 800);
            Controls.Add(b1);
            Controls.Add(b2);
            Controls.Add(lb);
            Controls.Add(b2b);
            Controls.Add(b3);

            lb.MouseEnter += delegate {
                b2.Visible = true;
            };
            lb.MouseLeave += delegate {
                b2.Visible = false;
            };
        }
    }
}

要解决此问题,一种解决方案是添加此代码:

    protected override Point ScrollToControl(Control activeControl) {
        return this.AutoScrollPosition;
    }

解决方案来自: Why does clicking in a text box cause an AutoScroll panel to scroll back to the top?

答案 1 :(得分:0)

没有重复。听我说你做的不仅仅是改变Visible属性。无论何时指定Location属性,都必须添加AutoScrollPosition以补偿滚动状态。如果这没有帮助,请发布代码。

答案 2 :(得分:0)

您是否验证了更改两个控件可见性的顺序? 自动滚动设置为true的容器上的滚动条将显示和消失,具体取决于控件可见区域之外的控件的位置。不可见的控件不计算在内。 因此,如果您在任何时候使两个控件都不可见,则滚动条将消失。当一个控件可见时,它们将返回。因此,为了确保您没有跳转滚动条位置和控件位置,您应该确保在任何时候都没有控件不可见。另一种解决方案是在容器上具有伪可见控制。这是一个控件,其可见性设置为true,但实际上对用户不可见(例如背景颜色的点,没有文本的标签......)。将此控件放在最远的位置x,y,滚动条将永远不会消失..