【问题标题】:Enum getting cast to string when bound with custom converter与自定义转换器绑定时,枚举被强制转换为字符串
【发布时间】:2020-12-11 02:46:30
【问题描述】:

问题概述

我有一个自定义的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, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return Binding.DoNothing
    End Function
End Class

复制步骤

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

代码说明

如果不清楚代码应该做什么,我会稍微解释一下。

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

【问题讨论】:

  • 如何定义两个枚举,一个用于支持字段ChosenThing,一个仅用于UI,其中包含“无”值(设置为-1)?您已经有一个绑定到组合框的单独属性,您可以在其中在支持字段枚举和 UI 枚举之间“转换”。那么你就不会设置OpenFoo = Nothing,而是设置OpenFoo = New Foo With { .SelectableChosenThing = ThingEnumForUI.Nothing }。我确实意识到这并不能回答您的 why 问题(因此是评论),但它可能会解决您的问题。
  • @SeanSkelly 在完整的应用程序中,将OpenFoo 设置为Nothing 意味着当前没有正在编辑Foo 实例。这在应用程序的逻辑中使用。

标签: wpf vb.net data-binding enums ivalueconverter


【解决方案1】:

经过一番调查,问题出在ComboBox 控件上。当ComboBox的选中项为null时,将null的显示值替换为String.Empty。这是来自.NET Reference Source for ComboBox.UpdateSelectionBoxItem的sn-p:

...

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

...

这发生在考虑任何DataTemplates 之前,所以当我的DataTemplate get 被调用时,它被赋予String.Empty 的值来显示而不是null

解决办法是

  • DataTrigger 添加到ContentControlStyle 以检查String.Empty 并且在这种情况下不使用转换器。
  • 修改EnumDisplayConverter 以检查非Enum 值并返回DependencyProperty.UnsetValue

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2012-08-25
    • 2019-08-19
    • 1970-01-01
    • 2012-01-03
    • 2020-02-20
    相关资源
    最近更新 更多