在wpf中使用带枚举的转换器 [英] Using converters with enums in wpf

查看:285
本文介绍了在wpf中使用带枚举的转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在组合框中显示之前更改枚举字符串值。在这种情况下,我希望橙子显示为Juicy oranges等。



  <  窗口    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



标题 = Window1 高度 = 300 W宽度 = 300 >
< Window.Resources >


< local:EnumConverter x:Key = fruitImprover > < / local:EnumConverter >
< ObjectDataProvider MethodName = GetValue s

ObjectType = {x:Type System:Enum}

< span class =code-attribute> x:Key = deliciousFruits >
< ObjectDataProvider.MethodParameters >
< x:输入 TypeName = local:Window1 + Fruit / >
< / ObjectDataProvider.MethodParameters >
< / ObjectDataProvider >
< / Window.Resources >

< 网格 > ;
< Grid.ColumnDefinitions >
< ColumnDefinition 宽度 = * > < / ColumnDefinition >
< ColumnDefinition 宽度 = * > < / ColumnDefinition >
< ColumnDefinition 宽度 = * > < / ColumnDefinition >
< /Grid.ColumnDefinitions >
< Grid.RowDefinitions >
< RowDefinition 高度 = * > < / RowDefinition >
< RowDefinition 高度 = .25 * > < / RowDefinition >
< RowDefinition < span class =code-attribute>
高度 = * > < / RowDefinition >
< / Grid.RowDefinitions >

< ComboBox Grid.Column = 1 Grid.Row = 1 ItemsSource = {Binding Source = {StaticResource deliciousFruits},Converter = {StaticResource fruitImprover}} > < / ComboBox >

< / Grid >
< / Window >





window1后面的VB代码是

 < span class =code-keyword>公开  Window1 
公开 < span class =code-keyword> Enum Fruit
Oranges
苹果
李子
结束 枚举

结束





我的转换器类是:

 公共  EnumConverter 
< span class =code-keyword> Implements IValueConverter

公共 功能转换(值作为 对象,targetType 作为类型,参数作为 对象,culture As Globalization.CultureInfo)作为 对象 实施 IValueConverter.Convert

Dim f As Window1.Fruit = CType (value,Window1.Fruit)
选择 案例 f
案例 Window1.Fruit.Apples
返回 多汁苹果
案例 Window1.Fruit.Oranges
< span class =code-keyword>返回 甜橙
案例 Window1.Fruit.Plums
返回 紫色李子
结束 选择

结束 功能

公共 功能 ConvertBack(值 As 对象,targetType 作为类型,参数 As 对象,culture 作为 Globalization.CultureInfo) As 对象 实施 IValueConverter.ConvertBack
返回 4
结束 功能
结束





我收到以下错误消息当我尝试将转换为水果枚举时。



从'Fruit()'类型转换为类型'整数'无效。



有什么想法吗?

解决方案

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


< blockquote>是的,不要这样做(我从来没有设法让这种方法工作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 < span class =code-keyword> Object ,culture As CultureInfo) As 对象 实现 IValueConverter.Convert
Dim myEnum 作为 [枚举] = DirectCast (值,[枚举])
Dim description 正如 字符串 = GetEnumDescription(myEnum)
返回说明
< span class =code-keyword>结束 功能

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





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



Combobox XAML:



 < ;   combobox     itemssource  < span class =code-keyword> =  {Binding Source = {StaticResource deliciousFruits}} > ;  
< 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>


这篇关于在wpf中使用带枚举的转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆