Xamarin.Forms 自定义 DateTime BindableProperty BindingPropertyChangedDelegate

Xamarin.Forms Custom DateTime BindableProperty BindingPropertyChangedDelegate

我一直在研究 Ed Snider 的书 Mastering Xamarin.Forms。第 71 页指示创建一个 class,DatePickerEmtryCell,它继承自 EntryCell。 它显示添加以下 DateTime BindableProperty,但此方法现已弃用并生成错误。

public static readonly BindableProperty DateProperty = BindableProperty.Create<DatePickerEntryCell, DateTime>(p =>
     p.Date,
     DateTime.Now,
     propertyChanged: new BindableProperty.BindingPropertyChangedDelegate<DateTime>(DatePropertyChanged));

我认为我在以下方面走在正确的轨道上,但我不确定如何完成它并且完全卡住了:

public static readonly BindableProperty DateProperty =
     BindableProperty.Create(nameof(Date), typeof(DateTime), typeof(DatePickerEntryCell), default(DateTime),
      BindingMode.TwoWay, null, new BindableProperty.BindingPropertyChangedDelegate(

我以为会是这个

    new BindableProperty.BindingPropertyChangedDelegate(DatePickerEntryCell.DatePropertyChanged), null, null);    

但这是不正确的,还有我尝试过的无数其他排列。 我想要一些指导。

干杯

因为 DateProperty 是静态的,propertyChanged 委托也应该是静态的。因为它是 BindingPropertyChangedDelegate 类型。你可以这样试试:

public static readonly BindableProperty DateProperty = BindableProperty.Create(
        propertyName: nameof(Date),
        returnType: typeof(DateTime),
        declaringType: typeof(DatePickerEntryCell),
        defaultValue: default(DateTime),
        defaultBindingMode: BindingMode.TwoWay,
        validateValue: null,
        propertyChanged: OnDatePropertyChanged);

现在,您应该可以从代理访问代表您的 DatePickerEntryCell 元素的 BindableObject。您还可以访问 old/new 值。以下是从委托中检索控件的方法:

public static void OnDatePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var control = bindable as DatePickerEntryCell;
    if (control != null){
        // do something with this control...
    }
}

希望对您有所帮助!