【问题标题】:Xamarin.Forms Nullpointer when Converter Ressource called调用转换器资源时的 Xamarin.Forms Nullpointer
【发布时间】:2018-02-27 06:01:07
【问题描述】:

我创建了一个转换器:

namespace MoneyFox.Business.Converter
{
    public class InverseBoolConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(bool) value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return !(bool)value;
        }
    }
}

我在页面中添加了一个命名空间:

xmlns:converter="clr-namespace:MoneyFox.Business"

<ContentView.Resources>
    <converter:InverseBoolConverter x:Key="inverter" />
</ContentView.Resources>

<Button Text="{Binding LoginButtonLabel}" IsVisible="{Binding IsLoggedIn, Converter={StaticResource inverter}}" Command="{Binding LoginCommand}" />

当我现在导航到该页面时,它会因 NullPointerException 而崩溃。一旦我移除转换器,它就会再次工作。

   'Object reference not set to an instance of an object.'
   at MoneyFox.Business.Views.BackupPage.InitializeComponent()
   at MoneyFox.Business.Views.BackupPage..ctor()

我认为我的命名空间声明是错误的,但从我在这里看到的应该是正确的: https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_binding_basics/

在命名空间中找不到逆变器的编译也没有错误(当我故意将命名空间更改为错误的命名空间时出现)。

有人可以给我一个提示吗?

【问题讨论】:

  • 为什么要尝试将转换器应用于命令绑定?
  • @Jason 对不起,我在尝试后插入错误。我在最初的帖子中更正了它。谢谢指出:)
  • 你试过调试转换器代码吗?检查空值?
  • 是的,但它根本没有被调用。我也可以从 IsVisible 标记中删除转换器,只要资源定义仍然存在,它仍然会崩溃。

标签: xamarin.forms


【解决方案1】:

您缺少&lt;ResourceDictionary&gt; 元素:

xmlns:converter="clr-namespace:MoneyFox.Business"

<ContentView.Resources>
  <ResourceDictionary>
    <converter:InverseBoolConverter x:Key="inverter" />
  </ResourceDictionary>
</ContentView.Resources>

<Button Text="{Binding LoginButtonLabel}" IsVisible="{Binding IsLoggedIn, Converter={StaticResource inverter}}" Command="{Binding LoginCommand}" />

【讨论】:

    猜你喜欢
    • 2021-01-12
    • 1970-01-01
    • 2012-05-16
    • 2023-03-28
    • 2011-09-06
    • 2011-03-06
    • 2011-02-28
    • 2017-09-27
    • 2021-05-17
    相关资源
    最近更新 更多