Xamarin 表单:IValueConverter 在 Convert 方法中接收空值

Xamarin form: IValueConverter receive null value in Convert method

我有一个列表视图集,其中项目源作为子项。我想将一个子对象绑定到一个视图,该视图将通过转换器设置颜色。

调用了转换器方法,但我传入的值是 null

除了点,我还使用Path=/,但传递给转换器的值仍然是null。如果我绑定 属性,它很好,但不是当前项目。

<ListView x:Name="childListView" 
    VerticalOptions="FillAndExpand" 
    HasUnevenRows="true" 
    ItemSelected="OnItemSelected"
    ItemTapped="OnItemTapped">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.View>
                    <StackLayout 
                        BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}" 
                        Spacing="0" Padding="0" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                        <StackLayout Orientation="Horizontal" Spacing="10" Padding="0" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                            <StackLayout Orientation="Horizontal" HorizontalOptions="StartAndExpand">
                                <controls:CircleImage>
BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}" 

那条线可能是罪魁祸首。仅当页面的绑定上下文是单个 "AccountedTo" 属性 时才有效。将其更改为 "{Binding BackgroundProperty}" 其中 "BackgroundProperty" 是 "AccountedTo" 值。

Phatye 说的绝对正确

BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}"

是罪魁祸首。过去我也曾尝试将 {Binding .}{Binding Path=.} 与转换器一起使用,只是为了 运行 进入您正在 运行 遇到的相同空引用问题。看来 Xamarin 不喜欢这样。

正确的解决方案是传递要绑定的 属性 的正确路径:

假设 属性 是顶级 属性

BackgroundColor="{Binding Path=accounted, Converter={StaticResource accountedToColorConverter}}"

否则你可以这样做:

BackgroundColor="{Binding Path=topLevelProperty.accounted, Converter={StaticResource accountedToColorConverter}}"

这是一个有趣的行为。我最近在使用 CarouselView (Forms.Plugin) 时遇到了这个问题,并做了更多研究,结果发现每个 CarouselView 元素的 BindingContext 由于某种原因被设置了不止一次。

所以第一次,转换器获得 null 值,但最终,它被第二次调用并使用正确的值,所以我更改了我的转换器以优雅地处理 null 值,并且成功了。