在wpf中ListBox 控件如何添加二级目录
时间: 2024-02-01 16:15:08 浏览: 93
在WPF中,ListBox控件默认只能展示一级数据,但可以通过自定义数据模板来实现添加二级目录。具体实现步骤如下:
1. 创建一个ViewModel类。
```csharp
public class Item
{
public string Name { get; set; }
public ObservableCollection<Item> SubItems { get; set; }
}
```
2. 在MainWindow.xaml中添加ListBox控件,并设置其数据源为Item的ObservableCollection。
```xml
<ListBox ItemsSource="{Binding Items}">
</ListBox>
```
3. 创建一个DataTemplate作为ListBox的ItemTemplate,并将其设置为ListBox的ItemTemplate。
```xml
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<ListBox ItemsSource="{Binding SubItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Margin="20,0,0,0"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
```
4. 在MainWindow的构造函数中设置ListBox的DataContext为ViewModel的实例。
```csharp
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
```
这样就可以在ListBox中添加二级目录了。每个Item对象都包含一个Name属性和一个SubItems属性,SubItems是一个ObservableCollection,用于存储子项。在ListBox的ItemTemplate中,我们创建了一个嵌套的ListBox控件,并设置其ItemsSource为当前Item的SubItems属性,然后再为嵌套的ListBox设置一个DataTemplate用于显示子项。
阅读全文
相关推荐


















