ullstrm
ullstrm

Reputation: 10170

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));
        }
    }
}

Upvotes: 6

Views: 13377

Answers (1)

Jason
Jason

Reputation: 89214

You need to set the Label's BindingContext:

red.BindingContext = _todoItem;

Upvotes: 9

Related Questions