【问题标题】:Which event on a Control level is equivalent to Form.Load event?控制级别上的哪个事件等效于 Form.Load 事件?
【发布时间】:2018-02-19 10:15:14
【问题描述】:

我正在尝试在我的应用程序中创建多个自定义控件,例如:

Public Class CbsDataGridView
    Inherits DataGridView

    '...

    Private Sub CbsDataGridView_Enter(sender As Object, e As EventArgs) Handles MyBase.Enter
        'Code here omitted, not related to the question.
        LoadGrid()
    End Sub

    Private Sub LoadGrid()
        'Code here omitted, not related to the question.
    End Sub

    '...

End Class

Public Class CbsDateTimePicker
    Inherits DateTimePicker

    Private Sub CbsDateTimePicker_Enter(sender As Object, e As EventArgs) Handles MyBase.Enter
        'Code here omitted, not related to the question.
    End Sub

End Class

将这些控件添加到新的空表单时。这是我遇到的两种情况:

场景 1:

- Drag And Drop CbsDateTimePicker into the form
- Drag And Drop CbsDataGridView into the form
- Run Application - Load The New Form
- CbsDateTimePicker_Enter event fires.
- CbsDataGridView_Enter event doesn't fire.

场景 2:

- Drag And Drop CbsDataGridView into the form
- Drag And Drop CbsDateTimePicker into the form
- Run Application - Load The New Form
- CbsDataGridView_Enter event fires.
- CbsDateTimePicker_Enter event doesn't fire.

我想我没有理解 Controls 的 Enter 事件。

我正在寻找的是一个类似于Form.Load 事件的事件,该事件将在包含控件的表单加载时触发。

有没有直接的方法来实现这个功能?还是我应该寻找其他方式?

【问题讨论】:

  • Enter 事件将在控件使用鼠标或键盘获得焦点时触发。此外,每当您通过代码设置表单的活动控件时,该事件都会触发。
  • @RezaAghaei 这解释了我得到的不良行为。无论我首先添加什么控件,都会得到关注,因此会触发Enter 事件。对吗?
  • 基于TabIndex,他们在表单加载时获得焦点。

标签: vb.net winforms custom-controls


【解决方案1】:

Enter 事件将在使用鼠标或键盘激活控件时触发。此外,每当您通过代码设置表单的活动控件时,都会触发该事件。

控件没有类似于FormLoad 事件的Load 事件,但它们有一个虚拟的OnCreateControl,它在首次创建控件时被调用。您可以覆盖它并向该方法添加自定义逻辑,甚至为您的控件引发自定义 Load 事件。

【讨论】:

  • 似乎调用LoadData 是这些控件所有者的责任。所有者更清楚何时是加载数据的合适时间。所以总的来说,我更喜欢公开LoadData,并通过拥有控件的表单显式调用它。
  • OnCreateControl 运行良好。我们试图尽量减少开发人员在使用此类控件时必须记住的内容。除非OnCreateControl 有任何问题,否则我将切换到LoadData 公共方法并调用它。或者只是一起切换到UserControl
  • LoadUserControl 事件也使用OnCreateControl 实现。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
  • 2016-03-25
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2011-05-07
  • 1970-01-01
相关资源
最近更新 更多