我試着以下枚舉綁定到組合框綁定轉換枚舉到一個ComboBox
Public Enum PossibleActions
ActionRead
ActionWrite
ActionVerify
End Enum
我不能改變枚舉本身,但我不希望顯示這些字符串。我的意圖是裁剪前綴'Action'並在ComboBox中顯示'Read','Write'和'Verify'。因此,我寫了一個ValueConverter
Public Class PossibleActionsConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
Dim actions() As PossibleActions
Dim strings() As String
actions = CType(value, PossibleActions())
ReDim strings(actions.GetUpperBound(0))
For i = 0 To actions.GetUpperBound(0)
strings(i) = actions(i).ToString.Substring(6)
Next
Return strings
End Function
Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
Dim s As String
s = CStr(value)
Return [Enum].Parse(GetType(PossibleActions), "Action" & s)
End Function
End Class
我的XAML看起來像
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:StepEditor"
[...]
<Window.Resources>
<ObjectDataProvider x:Key="possibleActionsEnum" MethodName="GetValues"
ObjectType="{x:Type sys:Enum}">
<ObjectDataProvider.MethodParameters>
<x:TypeExtension Type="local:PossibleActions"></x:TypeExtension>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<local:PossibleActionsConverter x:Key="possibleActionsConverter"></local:PossibleActionsConverter>
</Window.Resources>
[...]
或者:
<ComboBox ItemsSource="{Binding Source={StaticResource possibleActionsEnum}, Converter={StaticResource possibleActionsConverter}}"
SelectedItem="{Binding SelectedAction}"></ComboBox>
Or:
<ComboBox ItemsSource="{Binding Source={StaticResource possibleActionsEnum}, Converter={StaticResource possibleActionsConverter}}"
SelectedItem="{Binding SelectedAction, Converter={StaticResource possibleActionsConverter}}"></ComboBox>
我的問題是所選項目的綁定。它失敗了,但我不明白爲什麼。