与自定义转换器绑定时,枚举被强制转换为字符串

如何解决与自定义转换器绑定时,枚举被强制转换为字符串

问题概述

我有一个名为IValueConverter的自定义EnumDisplayConverter。应该使用一个Enum值并返回名称,以便可以显示它。某种程度上,即使此转换器用于Enum类型的属性之间的绑定上,也向该转换器传递了String.Empty的值。当然,这会导致错误,因为String不是Enum,更不用说这是真的。

要复制的代码

以下代码可用于重现该错误。复制步骤以及对代码含义的解释。

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:VBTest"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">

    <DockPanel>
        <ListBox Name="LB_Foos" DockPanel.Dock="Left" ItemsSource="{Binding FooOptions}" SelectionChanged="ListBox_SelectionChanged"/>
        
        <ComboBox ItemsSource="{x:Static local:MainWindow.SelectableThings}" SelectedItem="{Binding OpenFoo.SelectableChosenThing}" VerticalAlignment="Center" HorizontalAlignment="Center" Width="100">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl>
                        <ContentControl.Style>
                            <Style TargetType="ContentControl">
                                <Setter Property="Content" Value="{Binding Converter={x:Static local:EnumDisplayConverter.Instance}}"/>

                                <Style.Triggers>
                                    <DataTrigger Binding="{Binding}" Value="-1">
                                        <Setter Property="Content" Value="None"/>
                                    </DataTrigger>
                                </Style.Triggers>
                            </Style>
                        </ContentControl.Style>
                    </ContentControl>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </DockPanel>    
</Window>
Imports System.Collections.ObjectModel
Imports System.Globalization

Class MainWindow

    Shared Sub New()
        Dim Things = (From v As Thing In [Enum].GetValues(GetType(Thing))).ToList
        Things.Insert(0,-1)
        SelectableThings = New ReadOnlyCollection(Of Thing)(Things)
    End Sub

    Public Shared ReadOnly Property SelectableThings As IReadOnlyList(Of Thing)

    Public ReadOnly Property FooOptions As New ReadOnlyCollection(Of Integer)({1,2,3,4})

    'This is a placeholder method meant to set OpenFoo to a new instance of Foo when a selection is made.
    'In the actual application,this is done with data binding and involves async database calls.
    Private Sub ListBox_SelectionChanged(sender As Object,e As SelectionChangedEventArgs)
        OpenFoo = Nothing

        Select Case LB_Foos.SelectedItem
            Case 1
                OpenFoo = New Foo With {.ChosenThing = Nothing}
            Case 2
                OpenFoo = New Foo With {.ChosenThing = Thing.A}
            Case 3
                OpenFoo = New Foo With {.ChosenThing = Thing.B}
            Case 4
                OpenFoo = New Foo With {.ChosenThing = Thing.C}
        End Select
    End Sub

    Public Property OpenFoo As Foo
        Get
            Return GetValue(OpenFooProperty)
        End Get
        Set(ByVal value As Foo)
            SetValue(OpenFooProperty,value)
        End Set
    End Property
    Public Shared ReadOnly OpenFooProperty As DependencyProperty =
                           DependencyProperty.Register("OpenFoo",GetType(Foo),GetType(MainWindow))
End Class

Public Enum Thing
    A
    B
    C
End Enum

Public Class Foo

    Public Property ChosenThing As Thing?

    Public Property SelectableChosenThing As Thing
        Get
            Return If(_ChosenThing,-1)
        End Get
        Set(value As Thing)
            Dim v As Thing? = If(value = -1,New Thing?,value)
            ChosenThing = v
        End Set
    End Property

End Class

Public Class EnumDisplayConverter
    Implements IValueConverter

    Public Shared ReadOnly Property Instance As New EnumDisplayConverter

    Public Function Convert(value As Object,targetType As Type,parameter As Object,culture As CultureInfo) As Object Implements IValueConverter.Convert
        If value Is Nothing Then Return Nothing
        Return [Enum].GetName(value.GetType,value)
    End Function

    Public Function ConvertBack(value As Object,culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return Binding.DoNothing
    End Function
End Class

复制步骤

  1. 运行MainWindow
  2. 从左侧的ListBox中选择任何项
  3. ListBox
  4. 中选择其他项目
  5. 观察未处理的异常

代码说明

如果不清楚代码应该做什么,我将作一点解释。

Foo表示用户正在通过MainWindow编辑的数据对象。每个Foo都可以选择Thing拥有Thing也是一种选择,这就是ChosenThingThing?(即Nullable(Of Thing))的原因。

Null数据项在ComboBox中不起作用,因为Null的意思是“没有选择”。为了解决这个问题,我将-1的值添加到可选Thing值的列表中。在Foo.SelectableChosenThing中,我检查-1并将其转换为Null的实际值Foo.ChosenThing。这使我可以正确绑定到ComboBox

问题详细信息

仅在将OpenFoo设置为Nothing才被赋予新值之前,似乎只会出现该错误。如果我取出OpenFoo = Nothing行,一切正常。但是,在实际应用程序中,我想要将选择加载时将OpenFoo设置为Nothing-此外,它没有解释为什么这种情况首先发生

当所涉及的属性为预期的类型EnumDisplayConverter时,为什么value被传递为String类型的Thing?>

解决方法

经过一些调查,结果发现问题来自ComboBox控件。 ComboBox的选定项目为null时,它将null的显示值替换为String.Empty。这是.NET Reference Source for ComboBox.UpdateSelectionBoxItem的摘录:

...

// display a null item by an empty string
if (item == null)
{
    item = String.Empty;
    itemTemplate = ContentPresenter.StringContentTemplate;
}
 
SelectionBoxItem = item;
SelectionBoxItemTemplate = itemTemplate;

...

这是在考虑任何DataTemplate之前发生的,因此,在我的DataTemplate被调用时,它被赋予值为String.Empty而不是null来显示。

解决方案之一是

  • DataTrigger的{​​{1}}上添加ContentControl,以检查Style并且在这种情况下不使用转换器。
  • 修改String.Empty以检查非EnumDisplayConverter的值并返回Enum

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-