您的位置:首页 > 其它

WPF入门(七)绑定一个集合

2015-08-14 10:20 218 查看
当我完成下面的代码示例时,我乐了。我嘞个去,这不整个就是webForm么,只不过html变成了xaml。集合的绑定基本和webForm的绑定一样。先上代码:

1 //实体
2 class Person
3 {
4 public string Name { get; set; }
5 public int Age { get; set; }
6 }




代码

1 <Window x:Class="WpfAppListBinding.Window1"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 Title="Window1" Height="300" Width="591" Loaded="Window_Loaded">
5 <Grid>
6 <ListBox Margin="26,28,26,62" Name="listBox1" >
7 <ListBox.ItemTemplate>
8 <DataTemplate>
9 <StackPanel Orientation="Vertical">
10 <WrapPanel>
11 <TextBlock Text="{Binding Path=Name}" />
12 <TextBlock > 【</TextBlock>
13 <TextBlock Text="{Binding Path=Age}" />
14 <TextBlock >】</TextBlock>
15 </WrapPanel>
16 </StackPanel>
17 </DataTemplate>
18 </ListBox.ItemTemplate>
19 </ListBox>
20 </Grid>
21 </Window>
2




代码

1 /// <summary>
2 /// Window1.xaml 的交互逻辑
3 /// </summary>
4 public partial class Window1 : Window
5 {
6 public Window1()
7 {
8 InitializeComponent();
9 }
10
11 private void Window_Loaded(object sender, RoutedEventArgs e)
12 {
13 List<Person> lst = GetPersonListFromDatabase();
14 listBox1.ItemsSource = lst;
15 }
16
17 private List<Person> GetPersonListFromDatabase()
18 {
19 List<Person> lst = new List<Person>();
20 for (int i = 0; i < 10; i++)
21 {
22 lst.Add(new Person()
23 {
24 Name = "张" + i,
25 Age = i * 10
26 });
27 }
28 return lst;
29 }
30 }

2

基本步骤是:

1.拖一个Listbox到页面。

2.编写ListBox内的ListBox.ItemTemplate 项模板。在模板内处理数据绑定的控件。

3.在后台代码里指定数据源

     List<Person> lst = GetPersonListFromDatabase();
listBox1.ItemsSource = lst;

F5运行。OK。。。

不过,不过。我怎么没见到GridView? 怎么少了那么强大的控件呢。更多控件的使用我们会慢慢接触到。

待续ing...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: