This article is basically a secondary post (a small amount of rewriting is made on the basis of more databinding and custom controls, for the purpose of learning ^_^)
Purpose:
Display the user list on the page (display the user name and age of each user)
Ideas:
Define a user class to describe each user;
Defines an users class to store multiple users;
Define a userview Control for formatting and displaying each user;
Display the user list through the ListBox control on the final page;
The Code :
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= NewObservablecollection<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;
}
Data Binding in WPF is very interesting and worthy of in-depth research.