一次重置多个UserControl的属性

时间:2018-04-05 12:22:45

标签: vb.net properties user-controls visual-studio-2017

我想使用此Sub,以便立即重置一些UserControl的属性。实际上,仅重置BackColor的{​​{1}}值。如何“转换”它以重置多个属性?

UserControl

2 个答案:

答案 0 :(得分:2)

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

    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

答案 1 :(得分:1)

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

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