2016-01-12 41 views
0

下面是一個自定義的控制BindableProperty定義:BindableProperty吸氣返回null

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上的控制,我可以看到在propertyChangingnewValue設置爲正確的對象。同樣在ItemsSource屬性的設置器中,value變量採用正確的值。在BindNodeIcons()方法中,我訪問ItemsSource屬性,它返回null。我在代碼中看不到任何錯誤,但仍然存在。

+0

,可以確認投是否工作正常? 「itemsSource」行上的「itemsSource」的值是多少? – Slepz

+0

「return itemsSource」行上的「base.GetValue(ItemsSourceProperty)」和「itemSource」爲空。我立即調用它,我設置了屬性,但它只返回null。 –

+0

我正在查看代碼,我幾乎完全一樣的東西(除了字符串,而不是節點)。我可以看到的唯一區別是,我使用默認(IEnumerable )而不是null作爲defaultValue在bindableProperty構造函數中,並且我不調用setter中的任何內容(而您調用BindNodeIcons())。我很難過。也許嘗試改變你的默認值,並確保你在BindNodeIcons中不會做任何會與屬性混淆的東西 – Slepz

回答

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


    } 
在getter方法的ItemsSource