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

问题描述

问题概述

我有一个名为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