【发布时间】: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