實例講解WPF數(shù)據(jù)綁定技巧
作者:佚名
WPF數(shù)據(jù)綁定在WPF學(xué)習(xí)中是一個相當有意思的東西,值得我們?nèi)ド钊氲难芯俊T谶@篇文章中我們以一個實例來向大家簡單介紹一下相關(guān)知識。
WPF工具是一款幫助開發(fā)人員簡便實現(xiàn)圖形界面顯示的相關(guān)方法。在這篇文章中,我們就為大家詳細介紹下有關(guān)WPF數(shù)據(jù)綁定的一些基礎(chǔ)知識。#t#
目的:
在頁面上呈現(xiàn)用戶列表(顯示每個用戶的用戶名和年齡)
思路:
定義一個User類,用以描述每個用戶;
定義一個Users類,用以存儲多個用戶;
定義一個UserView控件,用以格式化顯示每個用戶;
在最終的頁面上通過ListBox控件顯示用戶列表;
以下為各個部分的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ù)綁定非常有意思,值得深入研究。
責任編輯:曹凱
來源:
IT168