A quick look at compiler generated files (.xaml.g.cs) - you will notice that these private fields are assigned in InitializeComponent method:[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]private void InitializeComponent(){ global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(BaseSettingsElement)); headText = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.Label>(this, "headText");}因此,这似乎是由于调用InitializeComponent和PropertyChangedHandler的顺序引起的问题. Therefore, this seems to be a problem caused due to the order in which InitializeComponent and PropertyChangedHandler are called. 在第一种情况下,显式设置属性时,这是方法被调用的顺序.In first case, when property is explicitly set, this is the order the methods are called.InitializeComponent -StartInitializeComponent -EndHeadTextColor -PropertyChanged在第二种情况下,使用全局样式设置属性时,顺序为:While, in second case, while using global style to set properties, the order is: HeadTextColor -PropertyChangedInitializeComponent -StartInitializeComponent -End看起来该属性是在基类构造函数中的某个位置设置的.因此,NullReferenceException是预期的.Looks like the property is set somewhere in a base class constructor. So the NullReferenceException is expected.有两种解决方法. 解决方案1(推荐) 代替使用属性更改的处理程序,而使用Binding设置内部子控件的属性,父节点为Source.例如:Instead of using property-changed handler, use Binding to set properties on inner-child controls, with parent node as Source. For e.g:<?xml version="1.0" encoding="UTF-8"?><ContentView xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="RemoteControlApp.CustomViews.BaseSettingsElement" xmlns:custom="clr-namespace:RemoteControlApp.CustomViews;assembly=RemoteControlApp" x:Name="_parent"> <ContentView.Content> <!-- .... --> <Label TextColor="{Binding HeadTextColor, Source={x:Reference _parent}}" /> 解决方案2 或者,在InitializeComponent之后设置内部控件的属性. Or, set inner control's properties after InitializeComponent. public MyView(){ Debug.WriteLine("InitializeComponent -Start"); InitializeComponent(); Debug.WriteLine("InitializeComponent -End"); //InitializeControl(); this.headText.TextColor = HeadTextColor;} 注意::在第二种解决方案中,您仍然需要更改属性的处理程序.否则,在XAML中显式设置属性不会将更改传播到内部控件.我猜想是为了进行空检查. Note: In second solution, you will still need the property-changed handler. Otherwise, explicitly setting properties in XAML will not propagate the change to inner controls. I guess a null check is in order for that. 这篇关于当我尝试将全局样式应用于Xamarin Forms中的自定义ContentView时发生NullReferenceException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-29 13:38