父面板的MouseWheel-子级的通过事件

时间:2019-07-20 12:22:12

标签: c# winforms

我有一个Custom面板,其中包含4个标签(在粘贴示例中,我已删除了我未使用的2个标签的定义)。 就像我在数组中拥有的许多记录一样,此自定义面板会动态添加到面板中。 父面板启用了“水平滚动” = false,因为我只能垂直滚动。 一切正常,因为我可以在垂直滚动条上使用鼠标,也可以滚动面板容器。但是,当我想使用鼠标滚轮滚动所有自定义面板(子对象)时,它什么也不做。 我在此站点上尝试了许多适用于其他解决方案的解决方案,但是它们都不适合我,我也不知道为什么。

我了解到面板必须具有焦点才能滚动,并且必须将OnMouseWheel事件传递给子级的父级。但是我做不到,我也不知道该怎么做。

我的自定义面板(子级):

public class PlaylistRecords : Panel
{
    public Label lblRecordNumber { get; private set; }

    private Label lblRecordName;

    public static int RecordNumber { get; set; }
    public static String RecordName { get; set; }

    public PlaylistRecords(
            int RecordNumber, 
            String RecordName
            )
    {
        InitializeComponent();
        this.Size = new System.Drawing.Size(800,50);
        this.BackColor = System.Drawing.Color.FromArgb(20,20,20);

        PlaylistRecords.RecordNumber = RecordNumber;
        PlaylistRecords.RecordName = RecordName;

        this.lblRecordNumber.Text = PlaylistRecords.RecordNumber.ToString()+".";
        this.lblRecordName.Text = PlaylistRecords.RecordName;

        this.lblRecordNumber.Location = new System.Drawing.Point(2, (int)(this.Height - this.lblRecordNumber.Height) / 2);
        this.lblRecordName.Location = new System.Drawing.Point(
                    this.lblRecordNumber.Location.X+ this.lblRecordNumber.Width+2, 
                    (int)(this.Height - this.lblRecordName.Height) / 2);

    }

    private void InitializeComponent()
    {
        this.lblRecordNumber = new myLabel();
        this.lblRecordName = new myLabel();
        this.lblRegistPath = new myLabel();

        this.SuspendLayout();
        // 
        // lblRecordNumber
        // 
        this.lblRecordNumber.Name = "lblRecordNumber";
        this.lblRecordNumber.Size = new System.Drawing.Size(50, 23);

        // 
        // lblRecordName
        // 
        this.lblRecordName.Name = "lblRecordName";
        this.lblRecordName.Size = new System.Drawing.Size(150, 23);

        // 
        // PlaylistRecords
        // 
        this.Controls.Add(this.lblRecordNumber);
        this.Controls.Add(this.lblRecordName);
        this.ResumeLayout(false);

    }
}

2 个答案:

答案 0 :(得分:1)

this.SetStyle(ControlStyles.Selectable, true);
this.TabStop = true;

用子控件(面板)的构造函数编写的这两行代码正在完成这项工作。

谢谢@Hans Passant的评论。 :)

答案 1 :(得分:0)

如果控件不接受事件,那么它们将被传递给父对象

lblRecordNumber.Enabled = false;
lblRecordName.Enabled = false;

或者,您可以将滚动事件传递给包含称为“父项”的控件

internal class myLabel : Label
{
    const int WM_MOUSEWHEEL = 0x020A;

    protected override void WndProc(ref Message m)
    {

        if (m.Msg == WM_MOUSEWHEEL)
            m.HWnd = this.Parent.Handle; 

        base.WndProc(ref m);
    }
}

并改用该控件。