WPF:数据绑定基础(临摹贴)
本文基本属于转贴(在More Databinding and Custom Controls基础上做了少量改写,出于学习的目的^_^)
目的:
在页面上呈现用户列表(显示每个用户的用户名和年龄)
思路:
定义一个User类,用以描述每个用户;
定义一个Users类,用以存储多个用户;
定义一个UserView控件,用以格式化显示每个用户;
在最终的页面上通过ListBox控件显示用户列表;
以下为各个部分的代码:
User.cs
public class User {
public string Name { get; set; }
public int Age { get; set; }
}
public class Users {
public ObservableCollection<User> UserList { get; set; }
public Users() {
this.UserList = new ObservableCollection<User>();
}
}
public string Name { get; set; }
public int Age { get; set; }
}
public class Users {
public ObservableCollection<User> UserList { get; set; }
public Users() {
this.UserList = new ObservableCollection<User>();
}
}
UserView.xaml
<WrapPanel>
<Label>Name:</Label>
<Label Name="lblName" Content="{Binding Path=Name}"/>
<Label>Age:</Label>
<Label Name="lblAge" Content="{Binding Path=Age}"/>
</WrapPanel>
<Label>Name:</Label>
<Label Name="lblName" Content="{Binding Path=Name}"/>
<Label>Age:</Label>
<Label Name="lblAge" Content="{Binding Path=Age}"/>
</WrapPanel>
Home.xaml
<Grid x:Name="gridMain">
<StackPanel>
<Label>UserList:</Label>
<ListBox ItemsSource="{Binding Path=UserList}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type kcl:User}">
<kucl:UserView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
<StackPanel>
<Label>UserList:</Label>
<ListBox ItemsSource="{Binding Path=UserList}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type kcl:User}">
<kucl:UserView />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
Home.xaml.cs
public Home() {
InitializeComponent();
Users pUsers = new Users();
pUsers.UserList.Add(new User() { Name = "Tom", Age = 10 });
pUsers.UserList.Add(new User() { Name = "Mike", Age = 5 });
pUsers.UserList.Add(new User() { Name = "Jack", Age = 1 });
DataContext = pUsers;
}
InitializeComponent();
Users pUsers = new Users();
pUsers.UserList.Add(new User() { Name = "Tom", Age = 10 });
pUsers.UserList.Add(new User() { Name = "Mike", Age = 5 });
pUsers.UserList.Add(new User() { Name = "Jack", Age = 1 });
DataContext = pUsers;
}
WPF中的数据绑定非常有意思,值得深入研究。