这段代码似乎很简单,但是运行需要很长时间。我已经制作了一个仅包含基本代码的示例项目,但是它仍然很慢。
我有一个带有按钮和面板的表格。在运行时,面板将动态填充约1700个自定义用户控件。自定义用户控件包含一个面板和一个属性。单击表单上的按钮会使每个用户控件交换其颜色。该操作应该一次全部发生,但是它是如此之慢,以至于我只能一次一行一行地观看每个用户控件开关的颜色
我可以暂停屏幕更新直到每个循环的整体运行之后,而不是一个一个地更新每个面板吗?
用户控制代码...
Public Class ucBox
Private _TurnedOn As Boolean
Public Property TurnedOn() As Boolean
Get
Return _TurnedOn
End Get
Set(ByVal value As Boolean)
_TurnedOn = value
If TurnedOn Then
PnlBox.BackColor = Color.Red
Else
PnlBox.BackColor = Color.LightGray
End If
End Set
End Property
Private Sub PnlBox_Click(sender As Object, e As EventArgs) Handles PnlBox.Click
If TurnedOn Then
TurnedOn = False
Else
TurnedOn = True
End If
End Sub
End Class
表单代码...
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim Rw As Int16 = 0, Col As Int16 = 0, x As Int16
Dim Box As ucBox
With btnTest
.Text = "Test Me"
End With
While Rw < PnlMain.Height - 10
While Col < PnlMain.Width - 10
Box = New ucBox
x = x + 1
With Box
.Top = Rw
.Left = Col
.TurnedOn = False
.Name = "Box_" & x
Col += .Width + 4
End With
PnlMain.Controls.Add(Box)
Box = Nothing
End While
Col = 0
Rw += 24
If x > 2000 Then Exit While
End While
Debug.Print("There are " & x & " boxes.")
End Sub
Private Sub btnTest_Click(sender As Object, e As EventArgs) Handles btnTest.Click
Dim StartTime As Date = Now
For Each b As ucBox In PnlMain.Controls
If b.TurnedOn Then
b.TurnedOn = False
Else
b.TurnedOn = True
End If
Next
Debug.Print("Test took " & Now.Subtract(StartTime).TotalMilliseconds)
End Sub
End Class
我很感谢任何想法。