【问题标题】:c# Panel with autoscroll - Srollbar position reset on a control focusc# 具有自动滚动功能的面板 - 在控件焦点上重置滚动条位置
【发布时间】:2012-02-16 07:10:11
【问题描述】:

这是一个windows窗体。

面板有 AutoScroll = True

我正在向主面板动态添加面板,最终超出主面板显示矩形。 然后将标签、组合框和文本框添加到添加的面板中。

如果我选择一个组合框或文本框,它将主面板滚动条位置重置为 0,并且组合框的下拉菜单将放置在屏幕 X、Y 上,如果滚动条没有重置。

我正在考虑在选择控件时保存滚动位置。经过测试,滚动位置似乎还没有重置,所以我可以在这里捕获它。然后在我希望的面板的某些事件上恢复滚动位置。 我正试图找出我将使用什么事件来恢复滚动位置。我还希望当我这样做时下拉菜单将放置在正确的 x,y 处。

更好的解决方案是创建基于面板控件的自定义控件并可能覆盖事件?这样我就不需要在每次使用滚动面板时都保存滚动位置而弄乱我的项目。

【问题讨论】:

  • 似乎如果我选择控件一次它会跳转到顶部,那么如果我在再次向下滚动后再次选择相同的控件,滚动条位置将不会被重置。

标签: c# winforms


【解决方案1】:

我在这里找到了问题的答案: Answer

public class CustomPanel : System.Windows.Forms.Panel
{
    protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)
    {
        // Returning the current location prevents the panel from
        // scrolling to the active control when the panel loses and regains focus
        return this.DisplayRectangle.Location;
    }
}

【讨论】:

  • 对于后代(如果链接断开):1. 子类面板 2. 覆盖 ScrollToControl() 以返回 this.DisplayRectangle.Location
  • 对于胆小的人:Subclassing 只涉及:将上面的代码粘贴到您的 Form.cs 中并更改两个位置在 Form.Designer.cs 中从 ..System.PanelCustomPanel
  • 当使用 TabPage 而不是 Panel 时,过程完全相同,但您必须从 DisplayRectangle.Location 的 X 和 Y 值中减去 3 个像素作为 TabControl 的边框。
【解决方案2】:

谢谢,这很好用,除了我必须调整面板底部的填充。仅供任何其他可能看到一些偏移量的人参考。

protected override System.Drawing.Point ScrollToControl(System.Windows.Forms.Control activeControl)
{
    Point retPt = DisplayRectangle.Location;
    retPt.Offset(new Point(-1*Padding.Left, -1*Padding.Bottom));

    return retPt;
}

【讨论】:

  • 这对我来说比其他解决方案更好,因为它考虑了填充。另一个解决方案是导致我的点击导致非常轻微的向上滚动。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 2021-04-02
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多