0
我有一個非常簡單的表單,我正在使用BindableProperty進行實驗。下面是形式標籤文本未從Bindable屬性更新
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyBindableProperty"
x:Class="MyBindableProperty.MainPage">
<StackLayout>
<local:MyLabel x:Name="BindingLabel" Text="{Binding Text}" MyText="{Binding Text}"
VerticalOptions="Center"
HorizontalOptions="Center" />
<Entry x:Name="BindingEntry" Text="{Binding Text, Mode=TwoWay}"/>
<Entry x:Name="BindingEntry2" Text="{Binding Text, Mode=TwoWay}"/>
<Button x:Name="BindingButton" Text="Reset"/>
</StackLayout>
</ContentPage>
而且這裏的XAML的背後是
public partial class MainPage : ContentPage
{
public DataSourceClass DataSourceObject { get; set; }
public MainPage()
{
DataSourceObject = new DataSourceClass { Text = "Test1" };
BindingContext = DataSourceObject;
InitializeComponent();
BindingButton.Clicked += BindingButton_Clicked;
}
private void BindingButton_Clicked(object sender, EventArgs e)
{
var boundText = this.BindingLabel.Text;
var boundMyText = this.BindingLabel.MyText;
DataSourceObject.Text = "Test2";
}
}
最後的代碼,這裏是在XAML中使用的自定義標籤類 -
public class MyLabel : Label
{
public string MyText
{
get
{
return (string)GetValue(MyTextProperty);
}
set
{
SetValue(MyTextProperty, value);
}
}
public static readonly BindableProperty MyTextProperty = BindableProperty.Create(nameof(MyText), typeof(string), typeof(MyLabel), "Test", BindingMode.TwoWay, propertyChanged: MyTextChanged);
public static void MyTextChanged(BindableObject bindable, object oldValue, object newValue)
{
((MyLabel)bindable).TextChanged(newValue.ToString());
}
public void TextChanged(string newText)
{
Device.BeginInvokeOnMainThread(() => this.Text = newText);
}
}
我的問題m有 當頁面初始化MyTextChanged處理程序觸發時,但不是在任何後續更改後 當單擊Reset按鈕時DataSou中的值無論我如何設置BindingLabel和BindingEntry2的值,rceObject.Text都會正確使用Entry元素 的值進行更新,但在頁面加載後,它們永遠不會反映DataSourceObject.Text的值。
任何幫助將不勝感激。
您可以從BindableObject繼承yuor類https://developer.xamarin.com/api/type/Xamarin.Forms.BindableObject/ – FDB
@FDB - 感謝您的評論。您提供的鏈接與解釋使用INotifyPropertyChanged時所用的鏈接相同,後者是我在答案中提到的。看來我只是誤解了BindableProperty和BindableObject的用途。 –