我想知道如何以动态方式填充ListBox。但我不想要自定义类,我只想要一个普通的选择器。
我通常用我自己的类做这样的事情:
<ListBox Name="itemList" SelectionChanged="itemList_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding title}"/>
<TextBlock Text="{Binding subtitle}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>我不知道的是如何简单地生成最简单的东西:像这样:
<ListBox>
<ListBoxItem Name="item1" Content="First item" />
<ListBoxItem Name="item2" Content="Second item" />
<ListBoxItem Name="item3" Content="Third item" />
</ListBox>你能举一个结构的例子吗?我不知道我是要用数据模板还是怎么的.
谢谢
已编辑:在我需要的内容中添加了Name属性
发布于 2011-03-31 18:45:16
您只需在您的DataContext中设置一个集合,并将其设置为ListBox.ItemsSource。然后,这将填充您的DataTemplate。
例如,请参阅:
<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"));
}
}示例来源:http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.itemssource(v=vs.95).aspx
编辑:根据评论中的讨论,也许你只需要一个简单的ItemsControl (因为你不需要保留选中的项目,或者更好地处理多个选择,这就是ListBox的用途)。
例如:
<ItemsControl ItemsSource="{Binding NavigateItems}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Label}"
Command="{Binding ButtonCommand}"
CommandParameter="{Binding URL}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>和:
public class NavigateItem
{
public String Label { get; set; }
public String URL { get; set; }
public NavigateItem(String label, String url)
{
this.Label = label;
this.URL = url;
}
}
public class NavigateItems : ObservableCollection<NavigateItem>
{
public NavigateItems()
{
Add(new NavigateItem("Google", "http://www.google.com");
Add(new NavigateItem("Bing", "http://www.bing.com");
}
}当然,设置ButtonCommand以导航到参数中传递的URL,但这取决于如何设置ViewModel /绑定。
发布于 2011-03-31 18:50:09
如果您没有或想要自定义类,例如,如果您只有一个字符串集合,那么您可以分配该字符串集合(List、IEnumerable、string[]等)。作为代码隐藏中ListBox的ItemsSource (或从XAML绑定它),它将使用TextBlock在每个ListBoxItem中呈现该内容。
https://stackoverflow.com/questions/5498535
复制相似问题