且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在wpf中使用带枚举的转换器

更新时间:2023-01-01 10:01:08

我会看下面的文章:​​使用DescriptionAttribute绑定到ComboBox的枚举 [ ^ ]


是的,不要这样做(我从来没有设法让这种方法工作0。你可以使用一种更好的方法,我认为它更易于使用。使用枚举上的[Description()]属性如下:





 公开 枚举水果
<说明( Juicy Oranges)>
橘子
<描述( 嘎吱嘎嘎的苹果)>
苹果
李子
结束 枚举





然后使用转换器从绑定对象中检索描述属性。

 公开  EnumDescriptionConverter 
Implements IValueConverter
私有 功能 GetEnumDescription(enumObj As [ 枚举])作为 字符串
Dim fieldInfo As FieldInfo = enumObj。[ GetType ]()。GetField(enumObj.ToString())

Dim attribArray As Object ()= fieldInfo.GetCustomAttributes( False

如果 attribArray.Length = 0 那么
返回 enumObj.ToString()
否则
Dim attrib As DescriptionAttribute = TryCast (attribArray( 0 ),DescriptionAttribute)
返回 attrib.Description
结束 如果
结束 功能

私有 功能 IValueConverter_Convert(value 作为 Object ,targetType As 类型,参数 As Object ,culture As CultureInfo) As 对象 实现 IValueConverter.Convert
Dim myEnum 作为 [枚举] = DirectCast (值,[枚举])
Dim description 正如 字符串 = GetEnumDescription(myEnum)
返回说明
结束 功能

私人 功能 IValueConverter_ConvertBack(值作为 对象,targetType 作为类型,参数作为 对象,culture 作为 CultureInfo)作为 对象 实现 IValueConverter.ConvertBack
返回 字符串 .Empty
结束 功能
结束





然后在组合框中将数据源设置为数据提供者并设置DisplayMemberPath转换器。



Combobox XAML:



 &LT ;   combobox     itemssource   =  {Binding Source = {StaticResource deliciousFruits}} &gt ;  
< combobox.itemtemplate >
< datatemplate >
< textblock text = {绑定转换器= {StaticResource fruitImprover}} > < / textblock >
< / datatemplate >
< / combobox.itemtemplate >
< / combobox >


I want to change the enum string value before I display it in a combo box. In this case I want "oranges to display as "Juicy oranges" etc.

<Window x:Class="Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        xmlns:System="clr-namespace:System;assembly=mscorlib"

        xmlns:local="clr-namespace:FruitProject"

    

    Title="Window1" Height="300" Width="300">
    <Window.Resources>

        
        <local:EnumConverter x:Key="fruitImprover"></local:EnumConverter>
            <ObjectDataProvider MethodName="GetValues"

                        ObjectType="{x:Type System:Enum}"

                        x:Key="deliciousFruits">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:Window1+Fruit" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
        
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height=".25*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        
        <ComboBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding Source={StaticResource deliciousFruits}, Converter={StaticResource fruitImprover}}"></ComboBox>
        
    </Grid>
</Window>



The VB code behind window1 is

Public Class Window1
    Public Enum Fruit
        Oranges
        Apples
        Plums
    End Enum
  
End Class



My converter class is:

Public Class EnumConverter
    Implements IValueConverter

    Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.Convert

        Dim f As Window1.Fruit = CType(value, Window1.Fruit)
        Select Case f
            Case Window1.Fruit.Apples
                Return "Juicy apples"
            Case Window1.Fruit.Oranges
                Return "Sweet Oranges"
            Case Window1.Fruit.Plums
                Return "Purple Plums"
        End Select

    End Function

    Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As Globalization.CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return 4
    End Function
End Class



I get the following error message when I try and convert value to a fruit enumeration.

Conversion from type 'Fruit()' to type 'Integer' is not valid.

Any ideas ?

I would look at the following article: Using DescriptionAttribute for enumerations bound to a ComboBox[^]


Yes, don't do it like that (I never managed to get that approach to work0. There is a much better approach you can use which I think is more re-usable. Use the [Description()] Attribute on your enum like this:


Public Enum Fruit
        <Description("Juicy Oranges")>
        Oranges
        <Description("Crunchy Apples")>
        Apples
        Plums
    End Enum



Then use a converter that retrieves description attributes from the bound object.

Public Class EnumDescriptionConverter
	Implements IValueConverter
	Private Function GetEnumDescription(enumObj As [Enum]) As String
		Dim fieldInfo As FieldInfo = enumObj.[GetType]().GetField(enumObj.ToString())

		Dim attribArray As Object() = fieldInfo.GetCustomAttributes(False)

		If attribArray.Length = 0 Then
			Return enumObj.ToString()
		Else
			Dim attrib As DescriptionAttribute = TryCast(attribArray(0), DescriptionAttribute)
			Return attrib.Description
		End If
	End Function

	Private Function IValueConverter_Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
		Dim myEnum As [Enum] = DirectCast(value, [Enum])
		Dim description As String = GetEnumDescription(myEnum)
		Return description
	End Function

	Private Function IValueConverter_ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
		Return String.Empty
	End Function
End Class



Then in your combo box set the datasource to your dataprovider and set the DisplayMemberPath to the converter.

Combobox XAML:

<combobox itemssource="{Binding Source={StaticResource deliciousFruits}}">
            <combobox.itemtemplate>
                <datatemplate>
                    <textblock text="{Binding Converter={StaticResource fruitImprover}}"></textblock>
                </datatemplate>
            </combobox.itemtemplate>
        </combobox>