Элемент управления TreeView поддерживает привязку к иерархическому источнику данных.Вы можете определить собственный класс для использования привязки.
Я сделал для вас пример кода:
<Grid>
<TreeView x:Name="treeview" ItemsSource="{x:Bind storageFolders,Mode=OneWay}">
<TreeView.ItemTemplate>
<DataTemplate x:DataType="local:FolderInfo">
<TreeViewItem ItemsSource="{x:Bind subFolders}" Content="{x:Bind FolderName}"/>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Button Content="folders" Click="Button_Click"></Button>
</Grid>
public class FolderInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(PropertyName));
}
}
private string _FolderName;
public string FolderName
{
get { return _FolderName; }
set
{
if (_FolderName != value)
{
_FolderName = value;
RaisePropertyChanged("FolderName");
}
}
}
public ObservableCollection<FolderInfo> subFolders { get; set; } = new ObservableCollection<FolderInfo>();
public override string ToString()
{
return FolderName;
}
}
public sealed partial class MainPage : Page
{
public ObservableCollection<FolderInfo> storageFolders { get; set; } = new ObservableCollection<FolderInfo>();
public MainPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker folderPicker = new FolderPicker();
folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
folderPicker.FileTypeFilter.Add(".txt");
var folder = await folderPicker.PickSingleFolderAsync();
var Folders = await GetFoldersAsync(folder);
foreach (var f in Folders)
{
storageFolders.Add(f);
}
}
private async Task<ObservableCollection<FolderInfo>> GetFoldersAsync(StorageFolder storageFolder)
{
var folders = await storageFolder.GetFoldersAsync();
ObservableCollection<FolderInfo> folderInfos = new ObservableCollection<FolderInfo>();
foreach (var f in folders)
{
folderInfos.Add(new FolderInfo() {FolderName=f.DisplayName,subFolders=await GetFoldersAsync(f) });
}
return folderInfos;
}
}
Затем, когда у вас появятся новые подпапки, выпросто нужно добавить его в коллекцию storageFolders
.