WPF中ListBox怎么绑定
时间: 2024-09-12 21:05:57 浏览: 83
在WPF(Windows Presentation Foundation)中,ListBox是一个常用的控件,用于显示一组选项供用户选择。要将数据绑定到ListBox,你可以按照以下步骤操作:
1. **准备数据源**:首先,你需要一个可以遍历的数据源,例如ObservableCollection、List<T> 或 DataTable。
```csharp
List<string> items = new List<string>() { "Item1", "Item2", "Item3" };
```
2. **设置DataContext**:确保当前窗口或UserControl的DataContext引用了包含数据源的对象。
```csharp
this.DataContext = items;
```
3. **XAML绑定**:在XAML文件中,使用`ItemsSource`属性将数据源绑定到ListBox上,并使用`ItemTemplate`来指定每个项的显示样式。
```xml
<ListBox Name="listBox">
<ListBox.ItemsSource>
<Binding Path="Items" />
</ListBox.ItemsSource>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
在这里,`{Binding}`会自动根据数据源中的元素类型来查找对应的属性。
阅读全文
相关推荐















