[英]Xamarin forms binding Label
基本上,我想發揮功能,當我在“編輯器”中輸入文本時,它將在標簽上顯示插入的數據。 而且,如果我要將頁面滑動到另一個頁面,則該數據應綁定到我輸入數據的上一頁中的該標簽。
所以我有便攜式課程。 在該類中,我具有方法public ContentPage CreatePage(MyObject thing)
在這里我定義了許多Labels,Box,Button等。但是,我將指出最重要的事情:在這里,我定義了Label和Editor:
public partial class CoolPage: CarouselPage
{
public CoolPage()
{
foreach (MyObject p in things)
{
Children.Add(CreatePage(p));
}
}
public ContentPage CreatePage(MyObject thing) {
var emptyLabel = new Label
{
Text = "Text",
WidthRequest = 50,
HeightRequest = 50,
BackgroundColor = Color.White
};
((StackLayout)page.Content).Children.Add(emptyLabel);
var inputNumb = new Editor
{
Text=thing.Number,
TextColor = Color.Black,
HorizontalOptions = LayoutOptions.Fill,
VerticalOptions = LayoutOptions.Fill,
IsVisible = true,
BackgroundColor = Color.White
};
inputNumb.SetBinding(Label.TextProperty, "Text");
inputNumb.BindingContext = thing.Number;
((StackLayout)page.Content).Children.Add(inputNumb);
}
}
我曾嘗試發起這樣的事件:
inputNumb.Completed += (sender, args) =>
{
inputNumb.SetBinding(Label.TextProperty, "Text");
inputNumb.BindingContext = thing.Number;
};
但它不起作用。 我認為是因為它采用相同的方法。 我也試圖通過在CreatePage
方法上實現這樣的行來超出方法范圍: inputCarNumb.Completed += InputCarNumb_Completed;
但是,當您定義變量inputNumb時,它無法識別,在其他情況下,我也不知道如何實現。 我知道這很簡單,但是我想通過SetBinding / BindingContext會錯過一些東西。
我這樣解決了這個問題:
emptyLabel.SetBinding(Label.TextProperty, "Text");
emptyLabel.BindingContext = inputNumb;
確保MyObject繼承並實現INotifyPropertyChanged,以便每當Number更改時都會觸發PropertyChanged。 我通常繼承自XLabs的ViewModel,並使用其SetProperty方法。 不要在事件中設置綁定。 但是SetBinding的第二個參數應該是“ Number”,這是MyObject的屬性名稱。 BindingContext也應該是thing。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.