创建 BindableProprties 时,GetValue 和 SetValue vs INotifyPropertyChanged.PropertyChanged?

GetValue and SetValue vs INotifyPropertyChanged.PropertyChanged when creating BindableProprties?

我通常通过创建可绑定属性来扩展控件,形式如下:

  public static readonly BindableProperty OnTextProperty = BindableProperty.Create(nameof(OnText),
            typeof(string), typeof(TextSwitch), defaultValue: string.Empty, defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: HandleOnTextPropertyChanged);

        private static void HandleOnTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
        {
            (bindable as TextSwitch)?.Rebuild();
        }

        public string OnText
        {
            get { return (string)GetValue(OnTextProperty); }
            set { SetValue(OnTextProperty, value); }
        }

对我来说,因为我做了一些 WPF,可绑定属性由两部分组成:静态只读 BindableProperty 字段,以及对应的 属性 with GetValue in getter and SetValue 在 setter 中。但是我偶然发现了这个:https://github.com/adamped/NavigationMenu/blob/master/NavigationMenu/NavigationMenu/NavigationItem.xaml.cs

刚刚触发 PropertyChanged 事件:

public static readonly BindableProperty TextProperty = BindableProperty.Create(
    nameof(Text),
    typeof(string),
    typeof(NavigationItem),
    string.Empty,
    propertyChanging: (bindable, oldValue, newValue) =>
    {
        var ctrl = (NavigationItem)bindable;
        ctrl.Text = (string)newValue;
    },
    defaultBindingMode: BindingMode.OneWay);

private string _text;

public string Text
{
    get { return _text; }
    set
    {
        _text = value;
        OnPropertyChanged();
    }
}

在没有 GetValueSetValue 的情况下,这如何与可绑定属性结合以使其工作?在哪些情况下我们需要使用一种方法而不是另一种方法?

编辑

显然我不习惯自绑定可重用控件的概念。但是调用 GetValueSetValue 不是绑定属性所必需的吗?

这两个实现是一样的。

GetValue(BindableProperty)SetValue 用于访问 BindableProperty 实现的属性值。也就是说,应用程序开发人员通常通过定义 public 属性 来为绑定 属性 提供接口,其 get 访问器将 GetValue(BindableProperty) 的结果转换为适当的类型,并且 returns 它,并且其设置访问器使用 SetValue 将值设置为正确的 属性。

你的成就

private static void HandleOnTextPropertyChanged(BindableObject bindable, object oldValue, object newValue)
    {
        (bindable as TextSwitch)?.Rebuild();
    }

相同
 propertyChanging: (bindable, oldValue, newValue) =>
{
    var ctrl = (NavigationItem)bindable;
    ctrl.Text = (string)newValue;
}

用过 OnPropertyChanged(); setValue方法