IamJohnny45 IamJohnny45 - 26 days ago 18
C# Question

How do I bind a Label to a property in Xamarin?

I have a content page "AnimalPage" with labels. I want to bind the labels.Text to the properties of a class so that the labels are automatically updated as the property values change.

The class is "Animal" which has two properties, girth & length. When either value is modified, a 3rd property "weight" is automatically calculated (note: the code that triggers the calcuation is not shown below). When the weight property changes, I want the weight Label on the content page to update automatically.

Many of the examples I've found on Xamarin are XAML which I'm not using.

At the moment, when the page loads, an initial value does show up in the Weight label so it seems like the binding is correct, but when the weight property changes, the label is not updated.

I've put breakpoints in the code and the calcWeight method is being called and the weight property is changing, but weightCell.cellText does not change.

What am I missing?

public class Animal {
public string Name { get; set; }

private double _girth;
// when girth changes, save the value and trigger a re-calculation of weight
public double girth { get { return _girth; } set { _girth = value; this.calcWeight(); } }
private double _length;

// same for length changes; save the value and trigger a re-calculation of weight
public double length { get { return _length; } set { _length = value; this.calcWeight(); } }

private double _weight;
public double weight { get { return _weight; } set { _weight = value; } }

public Animal()
{
...
}
...
public double calcWeight()
{
// formula for weight calculation goes here...
...
this.weight = weight;
return weight;

}
}


The page which displays this class is as follows:

internal class AnimalPage : ContentPage
{
private Animal animal { get; set; }

public AnimalPage(Animal animal)
{
this.animal = animal;
BindingContext = this.animal;
var weightCell = new ResultCell(); // ResultCell is a custom ViewCell
Binding myBinding = new Binding("weight");
myBinding.Source = this.animal;
weightCell.cellText.SetBinding(Label.TextProperty, myBinding);
...
}
}


For the sake of completeness, here is the ResultCell class which is just a custom ViewCell with two labels displayed horizontally.

public class ResultCell : ViewCell {
public Label cellLabel, cellText;

public ResultCell() {
cellLabel = new Label();
cellText = new Label();

var cellWrapper = new StackLayout {
...
Children = { cellLabel, cellText }
};
View = cellWrapper;
}
}

Answer

If you want your UI to automatically update when your data changes, your Animal class needs to implement INotifyPropertyChanged, and you need to fire the PropertyChanged event whenever your weight property is modified or recalculated. This event is what alerts the UI that it needs to refresh.

Comments