将私有子变成功能

时间:2013-07-27 20:48:27

标签: vb.net

我有以下程序:

    Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown

    Static Toggle As Boolean

    If myButton.Button = MouseButtons.Right Then

        If Toggle Then

            descForm.Hide()

        Else

            descForm.lblReportTitle.Text = "Ranges to Market"
            descForm.txtButtonDescription.Text = "Learn how you are currently paying specific departments or jobs compared to market. "
            descForm.Show()

        End If

    End If
    Toggle = Not Toggle

End Sub

由于我有大约9个按钮将执行相同的操作,但只更改descForm.lblReportTitle和descForm.txtButtonDescription中的文本,我该如何实现?

我想把sub变成一个函数,但我不知道如何实现它。

2 个答案:

答案 0 :(得分:1)

您可以为此子句添加处理程序。

Private Sub btnRptEmployeePayToMarket_MouseDown(ByValsender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown, btnAnotherone.MouseDown, etc...

答案 1 :(得分:1)

首先,您需要远离Toggle标志,以便知道何时切换特定按钮。

为此,我保留一个布尔对象字典,用按钮名称键入。当执行公共方法时,它会添加标志(如果它尚不存在),使用它来确定适当的行为,然后切换它。

以下是使用此逻辑重写代码:

Private m_cToggleFlags As New System.Collections.Generic.Dictionary(Of String, Boolean)

Private Sub btnRptEmployeePayToMarket_MouseDown(ByVal sender As Object, ByVal myButton As System.Windows.Forms.MouseEventArgs) Handles btnRptEmployeePayToMarket.MouseDown

    ToggleButton(DirectCast(sender, Control).Name, "Ranges to Market", "Learn how you are currently paying specific departments or jobs compared to market.")
End Sub

Private Sub ToggleButton(sButtonName As String, sReportTitle As String, sButtonDescription As String)

    If Not m_cToggleFlags.ContainsKey(sButtonName) Then
        m_cToggleFlags.Add(sButtonName, False)
    End If

    If m_cToggleFlags(sButtonName) 
        descForm.Hide()
    Else
        descForm.lblReportTitle.Text = sReportTitle
        descForm.txtButtonDescription.Text = sButtonDescription
        descForm.Show()
    End If

    m_cToggleFlags(sButtonName) = Not m_cToggleFlags(sButtonName)
End Sub