【问题标题】:GetValue and SetValue vs INotifyPropertyChanged.PropertyChanged when creating BindableProprties?创建 BindableProprties 时 GetValue 和 SetValue 与 INotifyPropertyChanged.PropertyChanged?
【发布时间】:2019-01-28 09:33:46
【问题描述】:

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

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

如何在没有GetValue 和SetValue 的情况下将其与可绑定属性结合使用?在哪些情况下我们需要使用一种方法而不是另一种方法?

编辑

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

【问题讨论】:

    标签: c# xamarin xamarin.forms inotifypropertychanged


    【解决方案1】:

    这两个实现是一样的。

    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();在setValuemethod

    【讨论】:

      猜你喜欢
      • 2018-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多