使用 XAML 元素填充 ListBox
< ListBox Width = " 150 " Margin = " 0,5,0,10 " >
< TextBlock Text = " TextBlock " />
< TextBox Text = " TextBox " />
< Button Content = " Button " />
< Rectangle Fill = " LightBlue " Height = " 20 " Width = " 100 " Margin = " 2,2,2,2 " />
< Ellipse Fill = " Coral " Height = " 20 " Width = " 150 " Margin = " 2,2,2,2 " />
</ ListBox >
使用 ItemsSource 屬性填充 ListBox
- 将 ItemsSource 屬性設定為您要顯示的集合。可以選擇設定 DisplayMemberPath,以指定要顯示在 ListBox 中的屬性。
< Grid >
< Grid.Resources >
< src:Customers x:Key = " customers " />
</ Grid.Resources >
< ListBox ItemsSource = " {StaticResource customers} " Width = " 250 " Margin = " 0,5,0,10 "
DisplayMemberPath = " LastName " />
</ Grid >
public class Customer
{
public String FirstName { get ; set ; }
public String LastName { get ; set ; }
public String Address { get ; set ; }
public Customer(String firstName, String lastName, String address)
{
this .FirstName = firstName;
this .LastName = lastName;
this .Address = address;
}
}
public class Customers : ObservableCollection < Customer >
{
public Customers()
{
Add( new Customer( " Michael " , " Anderberg " ,
" 12 North Third Street, Apartment 45 " ));
Add( new Customer( " Chris " , " Ashton " ,
" 34 West Fifth Street, Apartment 67 " ));
Add( new Customer( " Cassie " , " Hicks " ,
" 56 East Seventh Street, Apartment 89 " ));
Add( new Customer( " Guido " , " Pica " ,
" 78 South Ninth Street, Apartment 10 " ));
}
}
轉載于:https://www.cnblogs.com/landexia/archive/2011/03/14/1984319.html