Xamarin.Forms简单绑定到Label TextProperty

时间:2014-09-17 13:25:14

标签: c# xamarin xamarin.forms

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

1 个答案:

答案 0 :(得分:9)

您需要设置Label' BindingContext:

red.BindingContext = _todoItem;