0
votes

Below is the BindableProperty definition on a custom control:

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 ();
    }
}

When I set the BindingContext on the control I can see the newValue in propertyChanging is set to a correct object. Also in the setter of ItemsSource property the value variable takes the correct value. In the BindNodeIcons() method, I access ItemsSource property and it returns null. I can't see anything wrong in the code but still.

1
in the getter for ItemsSource, can you confirm the cast is working properly? What's the value of "itemsSource" on the line "return itemsSource;"Slepz
Both "base.GetValue (ItemsSourceProperty)" and "itemSource" on the line "return itemsSource" is null. I call it immediately I set the property but it only returns null.Élodie Petit
I'm looking at code where I do almost exactly the same thing (except string instead of Node). The only differences I can see are that I use default(IEnumerable<string>) instead of null for defaultValue in the bindableProperty constructor and I don't call anything in the setter (whereas you call BindNodeIcons()). I'm stumped. maybe try changing your default value and making sure you don't do anything in BindNodeIcons that would mess with the propertySlepz
I tried changing the code as you described but still getting null. Really strange, something is missing but can't see it at the moment.Élodie Petit
Yea bindings can be really difficult to debug. since you have a two-way binding, you may have a cause/effect relationship that you're not expecting. I'd just start commenting things out until it works and add them back one by one.Slepz

1 Answers

0
votes

Try the following:

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();
        }


    }