0

我正在尝试ContentAlignment通过组合框在 My.Settings 中存储和检索枚举。我已经在项目设置中设置了这个类型。我正在使用相关 Enum 值填充设置表单上的组合框:

With ControlAnchorCB
        .Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
End With

然后我尝试将组合框设置为 My.Settings 中的组合框:

ControlAnchorCB.SelectedItem = My.Settings.ConnectorControlAnchor

但没有价值显示。我还尝试将选定的组合框值保存回 My.Settings :

My.Settings.ConnectorControlAnchor = ControlAnchorCB.SelectedItem

但是,这会导致异常:“System.InvalidCastException:'从字符串“MiddleCenter”到类型“Integer”的转换无效。'”

更新:另一个限制是我在 Framework 3.5(必须是这个版本)和 vb.net 中编码。因此, Enum.TryParse 不可用。

我怎样才能做到这一点?

4

1 回答 1

0

在解决了很多问题之后:

    ' My.Settings.ConnectorControlAnchor Type is set to ContentAlignment in Project Settings.   
    
    Public Function TryParse(Of TEnum As {Structure, IConvertible})(ByVal value As String, <Out> ByRef result As TEnum) As Boolean
        Dim retValue = If(value Is Nothing, False, [Enum].IsDefined(GetType(TEnum), value))
        result = If(retValue, CType([Enum].Parse(GetType(TEnum), value), TEnum), Nothing)
        Return retValue
    End Function
    
    ' Populate ComboBox
    With ControlAnchorCB
        .Items.AddRange([Enum].GetNames(GetType(ContentAlignment)))
    End With
        
    ' Set combobox to value in My.Settings
    Dim ca As New ContentAlignment
    ControlAnchorCB.SelectedIndex = ControlAnchorCB.FindStringExact(My.Settings.ConnectorControlAnchor.ToString)

    ' To save value of combobox to My.Settings
    Dim ca As New ContentAlignment
    If TryParse(Of ContentAlignment)(ControlAnchorCB.SelectedItem, ca) Then My.Settings.ConnectorControlAnchor = ca
于 2021-12-28T14:14:08.153 回答