【问题标题】:Xamarin form: IValueConverter receive null value in Convert methodXamarin 形式:IValueConverter 在 Convert 方法中接收空值
【发布时间】:2017-10-21 13:59:55
【问题描述】:

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

转换器方法被调用,但我传入的值是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 属性的绑定中?如果您显示此 XAML 背后的代码,可能会更容易找到
  • 在 XAML 中,值转换器通常在 ResourceDictionary 中实例化,然后使用 StaticResource 标记扩展在绑定表达式中引用。请提供相关代码以获得帮助。
  • “.”我用在我的其他代码中,我在列表中有一个组绑定,在那个组中,我有字符串和其他对象组。这 ”。”表示列表中的当前项。我在模板选择器中使用了它,而不是在 IValueConverter 上使用它。

标签: xaml xamarin binding converter


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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}}"

    【讨论】:

    • 我遇到了类似的问题,当尝试使用 Path=. 在数据模板中传递项目时,我的转换器断点总是以 value null 触发。 @Ghasan 的帖子 stackoverflow.com/a/54798095/132599 是正确的 - 转换器将被多次调用,最初是 null,然后是对象。
    【解决方案3】:
    BackgroundColor="{Binding ., Converter={StaticResource accountedToColorConverter}}" 
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2016-12-08
      • 2018-06-06
      • 1970-01-01
      • 2017-02-18
      • 2022-06-13
      相关资源
      最近更新 更多