简体   繁体   中英

Xamarin.Forms simple binding to Label TextProperty

I am new to Xamarin.Forms and the binding concept. 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?

        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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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