一次重置多个 UserControl 的属性

Reset multiple UserControl's properties at once

我想用这个 Sub 来立即重置一些 UserControl 的属性。实际上,仅重置 UserControlBackColor 值。我怎样才能 "convert" 重置多个 属性?

Private Sub ResetControl(ByVal sender As Object, ByVal e As EventArgs)
    Dim _UserControl As UserControl1 = CType(Me.Control, UserControl1)
    Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)("BackColor")
    _PropertyDescriptor.ResetValue(_UserControl)
End Sub

您始终可以获取所有属性并为每个属性执行此操作

    For Each OneProperty In _UserControl.GetType.GetProperties()
        Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)(OneProperty.Name)
        If _PropertyDescriptor.CanResetValue(_UserControl) AndAlso _PropertyDescriptor.GetValue(_UserControl) IsNot Nothing Then
            _PropertyDescriptor.ResetValue(_UserControl)
        End If
    Next

或者如果您想使用名称,则来自字符串列表

    Dim ListOfPropertyNames As New List(Of String) From {"BackColor", "BorderStyle", "Dock"}
    For Each OneProperty In ListOfPropertyNames
        Dim _PropertyDescriptor As PropertyDescriptor = TypeDescriptor.GetProperties(_UserControl)(OneProperty)
        If _PropertyDescriptor.CanResetValue(_UserControl) Then ' this return tru if can be reset
            If _PropertyDescriptor.GetValue(_UserControl) IsNot Nothing Then ' check value if is not  nothing
                _PropertyDescriptor.ResetValue(_UserControl)
            End If
        End If
    Next

如果只需要某些属性,可以使用数组:

Private Sub ResetControl(ByVal sender As Object, ByVal e As EventArgs)
    Dim _UserControl As UserControl1 = CType(Me.Control, UserControl1)

    Dim _PropertyDescriptors As PropertyDescriptorCollection = TypeDescriptor.GetProperties(_UserControl)
    For Each propertyName as String in {"BackColor", "ForeColor"}
        _PropertyDescriptors(propertyName).ResetValue(_UserControl)
    Next


End Sub