我有一个带标签的内容页面“AnimalPage”。我想将labels.Text绑定到类的属性,以便标签随属性值更改而自动更新。如何将标签绑定到Xamarin中的属性?
的类是 “动物”,其具有两个属性,周长 & 长度。当任一值被修改时,将自动计算第三个属性“weight”(注意:触发计算的代码未在下面显示)。当权重属性更改时,我希望内容页上的权重标签自动更新。
我在Xamarin上找到的很多例子都是我没有使用的XAML。
目前,页面加载时,初始值确实显示在“重量”标签中,因此它看起来像绑定是正确的,但是当重量属性更改时,标签不会更新。
我已经在代码中放置了断点,并且正在调用calcWeight方法,并且weight属性正在更改,但weightCell.cellText不会更改。
我错过了什么?
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;
}
}
,显示这个类的页面如下:
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);
...
}
}
为了完整起见,这里是ResultCell类这仅仅是一个自定义的ViewCell与水平显示两个标签。
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;
}
}
是的,这工作。我在这里的例子:https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx 它是有道理的,但我见过Xamarin的例子,其中他们不从INotifyPropertyChanged继承,它仍然有效,所以我很困惑。我能想到的唯一的事情就是它们必须从已经实现的Xamarin类继承。 – IamJohnny45