Skip to content

数据绑定

L edited this page Jan 1, 2018 · 12 revisions

概念

数据绑定连接两个对象,称为源和目标。源对象提供数据。目标对象将消耗(并经常显示)来自源对象的数据。例如,Label(目标对象)通常将其Text属性绑定到源对象中的公共字符串属性。下图说明了绑定关系:
1
数据绑定的主要好处是您不再需要担心在视图和数据源之间同步数据。源对象中的更改被绑定框架自动推送到目标对象的幕后,目标对象中的更改可以选择性地推回到源对象

建立数据绑定是一个两步过程

目标对象的BindingContext属性必须设置为源
目标和来源之间必须建立约束。在XAML中,这是通过使用绑定标记扩展来实现的。在C#中,这是通过SetBinding方法实现的
有关数据绑定的更多信息,请参阅https://developer.xamarin.com/guides/xamarin-forms/xaml/xaml-basics/data_binding_basics/

使用内置模板TextCell进行数据绑定

var listView = new Xamarin.Forms.ListView
{
	RowHeight = 40
};
listView.ItemsSource = new TodoItem[] {
	new TodoItem { Name = "Buy 2 pears" },
	new TodoItem { Name = "Buy 3 oranges", Done=true} ,
	new TodoItem { Name = "Buy 5 mangos" },
	new TodoItem { Name = "Buy 7 apples", Done=true },
	new TodoItem { Name = "Buy 8 bananas", Done=true }
};
//TextCell是内置默认模板
listView.ItemTemplate = new DataTemplate(typeof(TextCell));
//绑定TextCell模板的Text属性对应TodoItem的Name
listView.ItemTemplate.SetBinding(TextCell.TextProperty, "Name");
Content = new StackLayout
{
	VerticalOptions = LayoutOptions.FillAndExpand,
	Children = { listView }
};

TodoItem类

public class TodoItem
{
	public string Name { get; set; }
	public bool Done { get; set; }
}

为ListView添加交互事件ItemSelected

listView.ItemSelected += async (sender, e) => {
	await DisplayAlert("Tapped!", e.SelectedItem + " was tapped.", "OK");
};

示例代码

https://github.com/zLulus/NotePractice/tree/dev3/Xamarin.Forms/XamarinDemo/XamarinDemo/XamarinDemo/Binding

Clone this wiki locally