在ResourceDictionary中为BindableProperty赋值自定义类实例遇空引用异常
问题:在ResourceDictionary中为Bar控件的BindableProperty赋值自定义Colors实例时触发NullReferenceException
自定义Colors类代码
namespace Foo { public class Colors { public Color Positive { get; set; } public Color Negative { get; set; } public Color Neutral { get; set; } public Colors() { } } }
Bar控件(包含BindableProperty)代码
namespace Foo { public class Bar : ContentView { public Colors Colors { get => (Colors)GetValue(ColorsProperty); set => SetValue(ColorsProperty, value); } public static BindableProperty ColorsProperty = BindableProperty.Create(nameof(Colors), typeof(Colors), typeof(Bar), null, BindingMode.OneWay); } }
styles.xaml代码
<?xml version="1.0" encoding="utf-8" ?> <ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:foo="clr-namespace:Foo;assembly=Foo"> <foo:Colors x:Key="colors" Positive="Green" Negative="Red" Neutral="Blue"/> ... <Style TargetType="foo:Bar"> <Setter Property="Colors" Value="{StaticResource colors}"/> </Style> </ResourceDictionary>
异常现象与详情
调试时Colors类构造函数断点已触发,说明实例已创建,但加载styles.xaml时触发Mono.Android中的未处理NullReferenceException,移除该属性赋值则运行正常。异常发生在App.xaml.g.cs中global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(App));语句之后。
异常栈信息:
System.NullReferenceException: Object reference not set to an instance of an object. at Android.Runtime.JNINativeWrapper._unhandled_exception (System.Exception e) [0x0000e] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:12 at Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V (_JniMarshal_PPL_V callback, System.IntPtr jnienv, System.IntPtr klazz, System.IntPtr p0) [0x0001d] in /Users/runner/work/1/s/xamarin-android/src/Mono.Android/Android.Runtime/JNINativeWrapper.g.cs:111 at (wrapper native-to-managed) Android.Runtime.JNINativeWrapper.Wrap_JniMarshal_PPL_V(intptr,intptr,intptr)
解决方案
- 将BindableProperty字段改为公共静态只读,并将默认值从
null改为new Colors(),符合Xamarin.Forms规范同时避免初始空值问题:public static readonly BindableProperty ColorsProperty = BindableProperty.Create(nameof(Colors), typeof(Colors), typeof(Bar), new Colors(), BindingMode.OneWay); - 检查Bar控件内部处理Colors属性的逻辑(如PropertyChanged回调、渲染逻辑),添加空值判断,避免空引用访问。
- 给Colors类的属性设置默认Color值,防止XAML初始化后属性仍为空:
public class Colors { public Color Positive { get; set; } = Color.Green; public Color Negative { get; set; } = Color.Red; public Color Neutral { get; set; } = Color.Blue; public Colors() { } } - 清理项目的bin/obj文件夹,重新生成解决方案,清除XAML编译缓存。
- 确认ResourceDictionary中
colors资源的定义在Style之前,避免静态资源查找失败。
内容的提问来源于stack exchange,提问作者Björn Albowitz
相关产品推荐
相关产品推荐

