我试图通过一个组合框在My.Settings中存储和检索一个My.Settings Enum。我已经在项目设置中设置了此类型。我正在使用相关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’的转换无效‘”。
更新:另一个限制是我在Framework3.5(必须是这个版本)和vb.net中编码。因此,Enum.TryParse不可用。
我怎样才能做到这一点?
发布于 2021-12-28 14:14:08
在费尽心思想要解决这个问题之后:
' 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 = cahttps://stackoverflow.com/questions/70498250
复制相似问题