實(shí)例講解WPF數(shù)據(jù)綁定技巧
WPF工具是一款幫助開(kāi)發(fā)人員簡(jiǎn)便實(shí)現(xiàn)圖形界面顯示的相關(guān)方法。在這篇文章中,我們就為大家詳細(xì)介紹下有關(guān)WPF數(shù)據(jù)綁定的一些基礎(chǔ)知識(shí)。#t#
目的:
在頁(yè)面上呈現(xiàn)用戶列表(顯示每個(gè)用戶的用戶名和年齡)
思路:
定義一個(gè)User類,用以描述每個(gè)用戶;
定義一個(gè)Users類,用以存儲(chǔ)多個(gè)用戶;
定義一個(gè)UserView控件,用以格式化顯示每個(gè)用戶;
在最終的頁(yè)面上通過(guò)ListBox控件顯示用戶列表;
以下為各個(gè)部分的WPF數(shù)據(jù)綁定代碼:
- 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>();- }
- }
- UserView.xaml
- <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>
- 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;
- }
WPF數(shù)據(jù)綁定非常有意思,值得深入研究。