【问题标题】:BindableProperty getter returns nullBindableProperty getter 返回 null
【发布时间】:2016-01-12 18:21:51
【问题描述】:

以下是自定义控件上的 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 时,我可以看到 propertyChanging 中的 newValue 设置为正确的对象。同样在ItemsSource 属性的设置器中,value 变量采用正确的值。在BindNodeIcons() 方法中,我访问ItemsSource 属性并返回null。我在代码中看不到任何错误,但仍然。

【问题讨论】:

  • 在 ItemsSource 的 getter 中,您能确认演员表工作正常吗? “return itemsSource;”行上的“itemsSource”的值是多少
  • “return itemsSource”行上的“base.GetValue (ItemsSourceProperty)”和“itemSource”均为空。我立即调用它我设置了属性,但它只返回 null。
  • 我正在查看我做几乎完全相同的事情的代码(除了字符串而不是节点)。我能看到的唯一区别是我在 bindableProperty 构造函数中使用 default(IEnumerable) 而不是 null 作为 defaultValue,并且我没有在 setter 中调用任何东西(而你调用 BindNodeIcons())。我难住了。也许尝试更改您的默认值并确保您没有在 BindNodeIcons 中做任何会与属性混淆的事情
  • 我尝试按照您的描述更改代码,但仍然为空。真的很奇怪,有东西不见了,但现在看不到。
  • 是的,绑定真的很难调试。因为你有一个双向绑定,你可能有一个你没有预料到的因果关系。我只是开始评论,直到它起作用,然后一一添加。

标签: xamarin.forms


【解决方案1】:

尝试以下方法:

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


    }

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2014-05-08
    • 1970-01-01
    • 2021-08-12
    • 2020-01-26
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2018-06-02
    相关资源
    最近更新 更多