代码之家  ›  专栏  ›  技术社区  ›  mshwf

创建BindableProperty时GetValue和SetValue与INotifyPropertyChanged.PropertyChanged的比较?

  •  0
  • mshwf  · 技术社区  · 7 年前

      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,bindable属性由两部分组成:静态只读BindableProperty字段和具有 GetValue 在getter和 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();
        }
    }
    

    如何将其与可绑定属性合并,以使其在无需绑定的情况下工作 方法 赋值 ?在哪些情况下,我们需要使用一种方法而不是另一种方法?

    显然,我不习惯自绑定可重用控件的概念。。但是他没有打电话 对绑定属性至关重要?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Leon    7 年前

    这两种实现是相同的。

    GetValue(BindableProperty) SetValue 用于访问由 BindableProperty . 也就是说,应用程序开发人员通常通过定义公共属性来为绑定属性提供接口,该公共属性的get访问器强制转换 GetValue(BindableProperty) 并返回它,以及set访问器使用的 赋值 在正确的属性上设置值。

    你的成就

    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

    推荐文章