BindableProperty getter返回null

时间:2016-01-12 18:21:52

标签: xamarin.forms

以下是自定义控件上的BindableProperty定义:

public static BindableProperty ItemsSourceProperty = 
BindableProperty.Create<NodeListView, IEnumerable<Node>> (ctrl =>
ctrl.ItemsSource,defaultValue: null,
defaultBindingMode: BindingMode.TwoWay,
propertyChanging: (bindable, oldValue, newValue) => {
        var ctrl = (NodeListView)bindable;
        ctrl.ItemsSource = newValue;
    });

public IEnumerable<Node> ItemsSource { 
    get {
        var itemsSource = (IEnumerable<Node>)GetValue (ItemsSourceProperty);
        return itemsSource;
    }
    set {
        SetValue (ItemsSourceProperty, value);
        BindNodeIcons ();
    }
}

当我在控件上设置BindingContext时,我可以看到newValue中的propertyChanging被设置为正确的对象。同样在ItemsSource属性的setter中,value变量采用正确的值。在BindNodeIcons()方法中,我访问ItemsSource属性并返回null。我仍然无法在代码中看到任何错误,但仍然存在。

1 个答案:

答案 0 :(得分:0)

尝试以下方法:

public class NodeListView : BindableObject
    {

        public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource), typeof(IEnumerable<Node>), typeof(NodeListView), propertyChanged: OnItemSourceChanged);

        public IEnumerable<Node> ItemsSource
        {
            get { return (IEnumerable<Node>)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }
        }

        private static void OnItemSourceChanged(BindableObject bindable, object oldValue, object newValue)
        {
            var nodeListView = bindable as NodeListView;
            nodeListView.BindNodeIcons();
        }


    }