Xamarin - 添加 OnPropertyChanged

Xamarin - add a OnPropertyChanged

我实现了 class 来创建自定义控件(如标签栏)。 IsSelected 布尔值用于更改该控件的某些属性。

public bool IsSelected
{
    get => (bool)GetValue(IsSelectedProperty);
    set => SetValue(IsSelectedProperty, value);
}

public static readonly BindableProperty IsSelectedProperty =
    BindableProperty.Create("IsSelected", typeof(bool), typeof(CustomTabBar), false, BindingMode.TwoWay, propertyChanged: IsSelectedPropertyChanged);



public static void IsSelectedPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    var control = (CustomTabBar)bindable;
    if (control != null)
    {
       control.IsSelected = (bool)newValue;
       control.Update();
    }
}

我需要检测使用此控件的父视图中的更改,以便根据 IsSelected 或不相应地显示内容。

我需要使用 INotifyPropertyChanged 吗?如何?

我在自定义控件中使用 INotifyPropertyChanged class,在父级中使用它的地方我放置了一个侦听器:

PropertyChanged += (object sender, PropertyChangedEventArgs e) =>
{
    // logic goes here 

    Console.WriteLine("A property has changed: " + e.PropertyName);
};

但它没有被解雇。

您需要的是一个很好的旧自定义事件,完全符合您在 C# 中的操作方式。

首先需要在自定义控件中引入事件class:

public delegate void IsSelectedHandler(object sender, EventArgs e);
public event IsSelectedHandler OnSelected;

然后,您很可能想在 属性 更改的回调方法中引发事件 IsSelectedPropertyChanged:

public static void IsSelectedPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
    if (OnSelected != null) 
    {
        OnSelected(this, new EventArgs(/* Whatever you want to publish here*/));
    }
}

完成所有管道后,您现在可以在父视图中订阅这些事件,如下所示:

yourTabControl.OnSelected += delegate {
    // Logic goes here
};