经常我们需要绑定的数据有多个,当添加到集合控件的对象类型结构比较复杂,我们希望自己来定义排版布局,这时可以使用ItemTemplate
用资源的定义
现在有数据
public class caddressBook
{
public caddressBook()
{
}
/// <summary>
/// 标识符
/// </summary>
public string id
{
set;
get;
}
/// <summary>
/// 通讯人姓名
/// </summary>
public string name
{
set;
get;
}
/// <summary>
/// 联系方式
/// </summary>
public string contact
{
set;
get;
}
/// <summary>
/// 工作地点
/// </summary>
public string address
{
set;
get;
}
/// <summary>
/// 城市
/// </summary>
public string city
{
set;
get;
}
/// <summary>
/// 备注
/// </summary>
public string comment
{
set;
get;
}
}
我们在MainPage.xaml用
<Page.Resources>
<DataTemplate x:Key="xaddressBook">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="auto"/>
</Grid.ColumnDefinitions>
<!--通讯人姓名、联系方式、工作地点、城市、备注-->
<TextBlock Grid.Column="0" >
通讯人姓名:
<Run Text="{Binding name}"/>
<LineBreak/>
联系方式:
<Run Text="{Binding contact}"/>
<LineBreak/>
工作地点:
<Run Text="{Binding address}"/>
<LineBreak/>
城市:
<Run Text="{Binding city}"/>
<LineBreak/>
备注:
<Run Text="{Binding remark}"/>
<LineBreak/>
</TextBlock>
</Grid>
</DataTemplate>
</Page.Resources>
列表
<ListView ItemTemplate="{StaticResource xaddressBook}" ItemsSource="{x:Bind view.addressBook,Mode=OneWay}"/>
使用System.Collections.ObjectModel.ObservableCollection
来作为list资源。
viewModel
public System.Collections.ObjectModel.ObservableCollection<caddressBook> addressBook
{
set;
get;
}
= new System.Collections.ObjectModel.ObservableCollection<caddressBook>()
{
new caddressBook()
{
name ="张三",
contact ="1",
address ="中国",
city =" ",
comment =" "
} ,
new caddressBook()
{
name ="张三",
contact ="1",
address ="中国",
city =" ",
comment =" "
}
};
因为想一个名字不是很简单,我就使用contact 不同来认为是不同的
修改addressBook前台会更新,ObservableCollection是包含了INotifyPropertyChanged
/// <summary>
/// 修改
/// </summary>
public void modify()
{
var taddressBook = new caddressBook()
{
name = "张三" ,
contact = "2" ,
address = "中国" ,
city = " " ,
comment = " "
};
addressBook.Add(taddressBook);
}
代码:https://code.csdn.net/lindexi_gd/lindexi_gd/tree/master/observable_collection