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

时间:2019-01-28 09:33:47

标签: c# xamarin xamarin.forms inotifypropertychanged

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

  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字段,以及一个对应的属性,其中getter为GetValue,setter为SetValue。但我偶然发现了这一点: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并不是必需的吗?

1 个答案:

答案 0 :(得分:0)

这两个实现是相同的。

GetValue(BindableProperty)SetValue用于访问BindableProperty实现的属性的值。也就是说,应用程序开发人员通常通过定义公共属性来提供绑定属性的接口,该公共属性的get访问器将GetValue(BindableProperty)的结果转换为适当的类型并将其返回,并且其set访问器使用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方法中