我发现Xamarin.Forms XAML非常令人沮丧。
如果我使用这个语法...
<ContentView.Resources>
<local:MyConverter1 x:Key="MyConverter1"/>
</ContentView.Resources>
在执行InitializeComponent()过程中,我会收到System.NullReferenceException异常。但根据调用堆栈、输出窗口或任何其他地方的信息,我无法知道出现了什么问题。
注意:这种语法在WPF中可以正常工作。
经过长时间的探索,我发现需要使用以下语法...
<ContentView.Resources>
<ResourceDictionary>
<local:MyConverter1 x:Key="MyConverter1"/>
</ResourceDictionary>
</ContentView.Resources>
同样适用于ListView DataTemplate。这会引发空引用异常...
<ListView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding Converter={StaticResource MyConverter1}}"/>
</DataTemplate>
</ListView.ItemTemplate>
由于正确的语法应该是这样的...
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding Converter={StaticResource MyConverter1}}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
再次强调,这个语法在WPF中很好用。我完全意识到Xamarin.Forms不是WPF,但每当我使用在WPF中有效的XAML结构时,我总是被空引用异常打击得疲惫不堪。
如何最好地调试Xamarin.Forms XAML问题?
目前,我只是将一些内容注释掉,直到它开始工作。这类似于在命令式代码中放置打印语句。声明式代码应该比命令式代码更好。
我做错了什么?
xmlns:local="clr-namespace:{ProperNameSpace};assembly={ProperAssembly}"
你能确认一下你是否有这个代码吗? - jdmdevdotnet