【问题标题】:Add logic inside button click inside a custom control在自定义控件内的按钮单击中添加逻辑
【发布时间】:2017-08-03 20:39:49
【问题描述】:

我正在制作一个看起来像这样的自定义控件(按钮右侧有一个标签):

我希望用户能够在他的代码中定义按钮的作用,但仍然在用户代码之上的点击事件上执行一些代码。

我要执行的操作:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Button1.Enabled = False
    Label1.ForeColor = Color.Gray
    Label1.Text = "In Progress"

End Sub

然后在执行此操作后,将触发用户的点击事件。

我怎样才能做到这一点?

【问题讨论】:

    标签: vb.net winforms events user-controls


    【解决方案1】:

    “用户”是指使用该用户控件的开发人员,对吗?好吧,最常见的事情是引发一个事件,下一个开发人员可以使用该事件来实现自己的逻辑。这与您所做的完全相同 - 您使用按钮的 Click-Event。

    所以基本上,拿你的代码并在下面添加RaiseEvent

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Button1.Enabled = False
        Label1.ForeColor = Color.Gray
        Label1.Text = "In Progress"
    
        ' this does not affect your code but provides a "hook" for
        ' other developers
        RaiseEvent OnButtonClick(Button1)
    
    End Sub
    

    现在你需要像这样定义事件本身...

    Public Event OnButtonClick(ByVal sender As Control)
    

    ...顺便说一句,您可以将其他东西(或根本没有)作为参数传递。将按钮作为发件人发送只是一种习惯。

    使用您的用户控件的开发人员可以在单击按钮后附加一个所谓的“处理程序”来实现代码,例如:

     AddHandler UserControl1.OnButtonClick, AddressOf OnUserControlButtonClick
    

    此代码行只应执行一次,因此通常放在Form_Load 事件中。

    现在,在这种情况下,按钮点击被路由到一个名为 OnUserControlButtonClick() 的方法,该方法符合事件的签名:这意味着它有一个参数,即发送者。

    Private Sub OnUserControlButtonClick(ByVal sender as Control)
        ' custom logic here ...
    End Sub
    

    网上有很多例子,你可以开始here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 2016-08-05
      • 1970-01-01
      • 2011-10-18
      • 2015-09-27
      相关资源
      最近更新 更多