简体   繁体   English

Xamarin.Forms简单绑定到Label TextProperty

[英]Xamarin.Forms simple binding to Label TextProperty

I am new to Xamarin.Forms and the binding concept. 我是Xamarin.Forms和绑定概念的新手。 Can someone please tell me why this is not working? 有人可以告诉我为什么这不起作用? The name of the object itself is changing when I'm pressing the button. 当我按下按钮时,对象本身的名称正在改变。 Why wont the Text-property update? 为什么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();
        };

The todoItem is an object of the class below. todoItem是下面类的对象。 The notification itself works, I am almost positive. 通知本身有效,我几乎是积极的。 I guess there's something wrong with my binding, or I am missing something with this concept. 我想我的绑定有问题,或者我错过了这个概念。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM