BindableBehavior没有更新绑定

时间:2018-03-15 18:01:46

标签: c# binding xamarin.forms

我有一个从可绑定行为类继承的自定义Behavior类 我有ItemSource属性,BindableProperty上的propertyChanged事件只在创建时调用而不是更改,即使我调用RaisePorpertyChanged

BindableBehaviorClass

 public abstract class BindableBehavior<T> : Behavior<T> where T : BindableObject
{
    public T AssociatedObject { get; private set; }

    protected override void OnAttachedTo(T visualElement)
    {
        base.OnAttachedTo(visualElement);

        AssociatedObject = visualElement;

        if (visualElement.BindingContext != null)
            BindingContext = visualElement.BindingContext;

        visualElement.BindingContextChanged += OnBindingContextChanged;
    }

    private void OnBindingContextChanged(object sender, EventArgs e)
    {
        OnBindingContextChanged();
    }

    protected override void OnDetachingFrom(T view)
    {
        view.BindingContextChanged -= OnBindingContextChanged;
    }

    protected override void OnBindingContextChanged()
    {
        base.OnBindingContextChanged();
        BindingContext = AssociatedObject.BindingContext;
    }
}

CustomListBehavior

   public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(nameof(ItemsSource),
        typeof(IEnumerable<IPerson>),
        typeof(CustomListBehavior), 
        defaultValue: null,
        propertyChanged: ItemsSourceChanged);
    public IEnumerable<IPerson> ItemsSource
    {
        get { return (IEnumerable<IPerson>)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

视图模型

  private ObservableCollection<IPreson> people = new ObservableCollection<IPerson>();


public ObservableCollection<IPerson>  People
    {
        get => people;
        set => SetProperty(ref people , value, nameof(People));
    }

1 个答案:

答案 0 :(得分:0)

在我的视图中,模型I改为而不是实例化局部变量 这个private ObservableCollection<IPreson> people = new ObservableCollection<IPerson>(); 我在创建类之后为其分配新值之前就已经完成了。