【问题标题】:Xamarin.Forms Custom DateTime BindableProperty BindingPropertyChangedDelegateXamarin.Forms 自定义 DateTime BindableProperty BindingPropertyChangedDelegate
【发布时间】:2017-04-08 12:12:54
【问题描述】:

我一直在研究 Ed Snider 的书 Mastering Xamarin.Forms。第 71 页指示创建一个继承自 EntryCell 的类 DatePickerEmtryCell。 它显示添加以下 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);    

但这是不正确的,以及我尝试过的无数其他排列。 我很想得到一些指导。

干杯

【问题讨论】:

    标签: c# xamarin.forms propertychanged


    【解决方案1】:

    由于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。您还可以访问旧/新值。以下是从委托中检索控件的方法:

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

    希望对你有帮助!

    【讨论】: