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));
}
}
}
The binding references the source object. To set the data binding, use the following two members of the target class: The BindingContext property specifies the source object. The SetBinding method specifies the target property and source property.
By default, Xamarin Forms will setup the binding so that it goes from the BindingContext (ViewModel) to the BindableObject (Page). This is called OneWay binding. However, there are two other options you can choose from. OneWayToSource is another option, and you can think of it as the reverse of OneWay binding.
However, the default binding mode for the Value property of Slider is TwoWay . This means that when the Value property is a data-binding target, then the target is set from the source (as usual) but the source is also set from the target. This is what allows the Slider to be set from the initial Opacity value.
When working with XAML in Xamarin. Forms, we use data-binding to connect properties on a binding context (such as a ViewModel) to controls in a page or a view. This powerful feature lets changes in the view automatically change the view model and vice-versa. However, the binding context is a runtime concept.
You need to set the Label's BindingContext:
red.BindingContext = _todoItem;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With