-
Notifications
You must be signed in to change notification settings - Fork 22
数据绑定
L edited this page Jan 2, 2018
·
12 revisions
数据绑定连接两个对象,称为源和目标。源对象提供数据。目标对象将消耗(并经常显示)来自源对象的数据。例如,Label(目标对象)通常将其Text属性绑定到源对象中的公共字符串属性。下图说明了绑定关系:
数据绑定的主要好处是您不再需要担心在视图和数据源之间同步数据。源对象中的更改被绑定框架自动推送到目标对象的幕后,目标对象中的更改可以选择性地推回到源对象
目标对象的BindingContext属性必须设置为源
目标和来源之间必须建立约束。在XAML中,这是通过使用绑定标记扩展来实现的。在C#中,这是通过SetBinding方法实现的
有关数据绑定的更多信息,请参阅https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_binding_basics/
1.XAML
2.C#
进行数据绑定
//Model
Employee employeeToDisplay = new Employee();
//输入框
var firstNameEntry = new Entry()
{
HorizontalOptions = LayoutOptions.FillAndExpand
};
//绑定 下面两个绑定,任选其一即可
this.BindingContext = employeeToDisplay;
firstNameEntry.SetBinding(Entry.TextProperty, "FirstName");
Employee类
实现接口INotifyPropertyChanged,FirstName在set时,触发OnPropertyChanged方法
public class Employee : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (value.Equals(_firstName, StringComparison.Ordinal))
{
// Nothing to do - the value hasn't changed;
return;
}
_firstName = value;
OnPropertyChanged();
}
}
void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
查看绑定结果
//查询按钮
Button getValueButton = new Button();
getValueButton.Text = "查看结果";
getValueButton.Clicked += (async (sender, e) =>
{
await DisplayAlert("绑定结果",$"当前Entry的Text是{firstNameEntry.Text},后台实体的FirstName是{employeeToDisplay.FirstName}","确定");
});
https://github.com/zLulus/NotePractice/tree/dev3/Xamarin.Forms/XamarinDemo/XamarinDemo/XamarinDemo/Bindings 的BindingFirstName