【发布时间】:2017-03-22 12:22:23
【问题描述】:
我有一个带有标签的内容页面“AnimalPage”。我想将labels.Text绑定到一个类的属性,这样标签会随着属性值的变化而自动更新。
类是“Animal”,它有两个属性,girth和length。当任一值被修改时,会自动计算第三个属性“weight”(注意:触发计算的代码未在下面显示)。当 weight 属性发生变化时,我希望内容页面上的 weight Label 自动更新。
我在 Xamarin 上找到的许多示例都是我没有使用的 XAML。
目前,当页面加载时,Weight 标签中确实显示了一个初始值,因此看起来绑定是正确的,但是当 weight 属性更改时,标签不会更新。
我已经在代码中设置了断点,并且调用了 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;
}
}
【问题讨论】:
标签: c# xamarin binding properties label