编辑:以下是一些代码隐藏的要点以及它报告的内容:https://gist.github.com/mattkenefick/5c4effdbad712eb1a42f6cf7207226a6
注意:这个问题特定于 InitializeComponent 调用中发生的情况,而不是其他很多事情。请完整阅读问题。
我有一个MyPage->BasePage->ContentPage
结构。如果BasePage
InitializeComponent()
执行,则 XAML 元素在MyPage
内失去作用域。这意味着我不能在没有获得 NullReferenceException 的情况下调用MyPage.MyListView.ItemSource = xyz
。
如果InitializeComponent()
调用只发生在MyPage
,那么一切正常(意味着它不会被调用BasePage
(
这个问题非常具体地涉及理解为什么BasePage.InitializeComponent()
调用会中断对 XAML 元素(如x:MyListView
(的引用。
Models
Pages
├ BasePage.xaml
| ⤷ BasePage.xaml.cs
└ MyPage.xaml
⤷ MyPage.xaml.cs
Views
App.xaml
⤷ App.xaml.cs
在我的MyPage.xaml
标记上,我有各种StackLayout元素,ListView等。这一切都存在于pages:BasePage.Content
标签中,如下所示:
<!-- for s/o: MyPage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<pages:BasePage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Namespace.Pages"
xmlns:views="clr-namespace:Namespace.Views"
x:Class="Namespace.Pages.MyPage">
<pages:BasePage.Content>
<ListView x:Name="ListViewView">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout>
<Image Source="{Binding imageUrl}" />
<Label Text="{Binding formattedDayOfWeek}" />
<Label Text="{Binding formattedDate}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</pages:BasePage.Content>
</pages:BasePage>
在我的MyPage.xaml.cs
类中,构造函数执行InitializeComponent()
方法。
以下是BasePage.xaml
的外观:
<!-- for s/o: BasePage.xaml -->
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="Namespace.Pages.BasePage"
x:Name="_parent">
<ContentPage.Content>
<StackLayout x:Name="VerticalLayout" BackgroundColor="#f1f1f1">
<ContentView
x:Name="cv"
x:FieldModifier="public"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
Content="{Binding Path=ViewContent, Source={x:Reference _parent}}" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
所以重申一下:
在MyPage.xaml.cs
中,我试图在从 REST 服务器异步获取后调用ListViewView.ItemsSource = SomeDataModel
。
如果扩展的BasePage.xaml.cs
类在其构造函数中调用InitializeComponent()
...设置项目源时,我将得到一个 NullReferenceException。
如果扩展的BasePage.xaml.cs
类没有在其构造函数中调用InitializeComponent()
...项目源设置正确,并显示列表。
有人可以向我解释为什么父InitializeComponent
调用会导致MyPage
类中的 NullReferences?
谢谢!
默认情况下,Xamarin 从 XAML 生成的变量是private
的,因此无法在继承的类中访问它们。
字段修改器允许您更改默认行为
<Label x:Name="publicLabel" x:FieldModifier="public" />
首先,我假设你说的是真的(我自己没有尝试过(。
如果是这种情况,发生这种情况是因为 XAML 不可像 C# 类那样可继承。因此,通过固有 XAML 页所做的是仅继承其 C# 代码,而不继承其 XAML 内容。考虑到这一点,InitializeComponent
不应该起作用。