【问题标题】:Xamarin Forms Nullable Property - Object reference not set to an instance of an objectXamarin Forms Nullable Property - 对象引用未设置为对象的实例
【发布时间】:2016-07-01 17:25:57
【问题描述】:

我是 Xamarin Forms 的新手,并试图在 XAML 中绑定一个可为空的属性:

 public DateTime? LocalExpiryDate  //property on Person class
    {
        get { return GetValue<DateTime>(); }
        set { SetValue(value); }
    }

 <Label Text="{Binding LocalExpiryDate}"/>

并在后面的代码中绑定为:

 InitializeComponent();
 MainStackLayout.BindingContext = member.Person;

即使当我尝试在 Android 模拟器上运行应用程序时该属性不为空,我也会收到错误“调用的目标已引发异常”,并深入了解该错误,我会收到一条消息“对象引用未设置为对象的实例"

如果我删除 ?使属性不可为空,只要有属性,应用程序就可以正常工作

是否无法绑定到可为空的属性,或者有没有办法解决这个问题?

谢谢

标记

【问题讨论】:

  • LocalExpiryDate 是您控制的 BindableProperty 吗?
  • 我不太明白 - 我正在使用 绑定到标签
  • 我想知道你在哪里声明LocalExpiryDate
  • LocalExpiryDate 是一个名为 Person 的实体的填充属性,其中包含数据。如果属性未设置为可为空,则工作正常,但一旦再次变为可为空,则失败 Person 模型上的其他属性绑定正常
  • 你能发布更多关于Person的信息吗?

标签: c# xamarin xamarin.forms


【解决方案1】:

据我了解您的问题。我有Page:

public partial class Page1 : ContentPage
{
    private Person _person;
    public Person Person
    {
        get { return _person; }
        set
        {
            _person = value;
            OnPropertyChanged();
        }
    }

    public Page1()
    {
        BindingContext = this;
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        Person = new Person() { Date = DateTime.Now };

        base.OnAppearing();
    }
}

我有Person:

public class Person : BindableObject
{
    private DateTime? _date;
    public DateTime? Date
    {
        get { return _date; }
        set
        {
            _date = value;
            OnPropertyChanged();
        }
    }
}

我有XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:CommonSample;assembly=CommonSample"
         x:Class="CommonSample.Page1">
  <StackLayout>
    <Label Text="{Binding Person.Date}"/>
  </StackLayout>
</ContentPage>

【讨论】:

  • 太棒了,BindableObject 有效。 Person 被标记为 Breeze.Sharp.BaseEntity 以与 Breeze Sharp 一起使用,但更改为 BindableObject 修复了它
猜你喜欢
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多