![](/img/trans.png)
[英]how to bind HorizontalOptions property of label in xamarin.forms
[英]How do I bind a Label to a property in Xamarin?
我有一個帶有標簽的內容頁面“ AnimalPage ”。 我想將labels.Text綁定到類的屬性,以便隨着屬性值的更改自動更新標簽。
該類是“ 動物 ”,具有兩個屬性, 周長和長度 。 修改任何一個值時,都會自動計算第三個屬性“ 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;
}
}
如果您希望用戶界面在數據更改時自動更新,則Animal類需要實現INotifyPropertyChanged ,並且每當修改或重新計算weight屬性時都需要觸發PropertyChanged事件。 此事件提醒UI需要刷新。
因為這花了我很長時間才弄清楚,所以我認為我應該發布更正的Animal類,以防其他人受到幫助。
public class Animal : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string Name { get; set; }
private double _girth;
public double girth { get { return _girth; } set { _girth = value; this.calcWeight(); } }
private double _length;
public double length { get { return _length; } set { _length = value; this.calcWeight(); } }
private double _weight;
public double weight { get { return _weight; } set { _weight = value; NotifyPropertyChanged(); } }
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public Animal()
{
...
}
...
public double calcWeight()
{
// formula for weight calculation goes here...
...
this.weight = weight;
return weight;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.