使用 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"));
}
}