我是Xamarin.Forms和绑定概念的新手.有人可以告诉我为什么这不起作用?当我按下按钮时,对象本身的名称正在改变.为什么Text-property不会更新?
var red = new Label { Text = todoItem.Name,BackgroundColor = Color.Red,Font = Font.SystemFontOfSize (20) }; red.SetBinding (Label.TextProperty,"Name"); Button button = new Button { Text = String.Format("Tap for name change!") }; button.Clicked += (sender,args) => { _todoItem.Name = "Namie " + new Random().NextDouble(); };
todoItem是下面类的对象.通知本身有效,我几乎是积极的.我想我的绑定有问题,或者我错过了这个概念.
public class TodoItem : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; string _name; public string Name { get { return _name; } set { if (value.Equals(_name,StringComparison.Ordinal)) { // Nothing to do - the value hasn't changed; return; } _name = value; OnPropertyChanged(); } } void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this,new PropertyChangedEventArgs(propertyName)); } } }
解决方法
您需要设置Label的BindingContext:
red.BindingContext = _todoItem;