У меня есть древовидное представление, в котором я загружаю все файлы и папки по пути. я использовал Microsoft Docs/Example
мои коды работают нормально, однако есть одна проблема! я вижу, что в древовидное представление добавлены пустые папки. я хочу удалить их/пропустить. я не знаю, как это сделать. для меня это немного сложно.
private async void FillTreeNode(TreeViewNode node)
{
// Get the contents of the folder represented by the current tree node.
// Add each item as a new child node of the node that's being expanded.
// Only process the node if it's a folder and has unrealized children.
StorageFolder folder = null;
if (node.Content is StorageFolder && node.HasUnrealizedChildren == true)
{
folder = node.Content as StorageFolder;
}
else
{
// The node isn't a folder, or it's already been filled.
return;
}
IReadOnlyList<IStorageItem> itemsList = await folder.GetItemsAsync();
if (itemsList.Count == 0)
{
// The item is a folder, but it's empty. Leave HasUnrealizedChildren = true so
// that the chevron appears, but don't try to process children that aren't there.
return;
}
foreach (var item in itemsList)
{
var newNode = new TreeViewNode();
newNode.Content = item;
if (item is StorageFolder)
{
// If the item is a folder, set HasUnrealizedChildren to true.
// This makes the collapsed chevron show up.
newNode.HasUnrealizedChildren = true;
}
else
{
if (item is StorageFile storageFile)
{
if (!AllowedExtensions.Contains(storageFile.FileType))
{
return;
}
}
// Item is StorageFile. No processing needed for this scenario.
}
node.Children.Add(newNode);
}
// Children were just added to this node, so set HasUnrealizedChildren to false.
node.HasUnrealizedChildren = false;
}
Применение:
StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(rootPath);
TreeViewNode itemNode = new TreeViewNode();
itemNode.Content = storageFolder;
itemNode.IsExpanded = true;
itemNode.HasUnrealizedChildren = true;
sampleTreeView.RootNodes.Add(itemNode);
FillTreeNode(itemNode);





этот код может исправить 2 проблемы: сначала пропустить пустую папку, во-вторых, исправить проблему, при которой не добавляются все элементы.
foreach (var item in itemsList)
{
var newNode = new TreeViewNode();
newNode.Content = item;
if (item is StorageFolder storageFolder)
{
var files = Directory.EnumerateFiles(storageFolder.Path, "*.*", SearchOption.AllDirectories)
.Where(s => AllowedExtensions.Contains(Path.GetExtension(s)));
if (files.Count() == 0)
{
continue;
}
// If the item is a folder, set HasUnrealizedChildren to true.
// This makes the collapsed chevron show up.
newNode.HasUnrealizedChildren = true;
}
else
{
if (item is StorageFile storageFile)
{
if (!AllowedExtensions.Contains(storageFile.FileType))
{
continue;
}
}
// Item is StorageFile. No processing needed for this scenario.
}
node.Children.Add(newNode);
}
Вам следует использовать привязку данных (для коллекций, классов, свойств и т. д.), выраженную в XAML, а не создавать элементы пользовательского интерфейса с помощью кода. Обычно это намного проще, поскольку все в UWP/WinUI3 (и то же самое было с WPF) создано для привязки данных. (такие шаблоны, как MVVM, существуют только для того, чтобы обеспечить привязку данных без кода). Некоторые вещи с помощью этих UI-фреймворков очень сложно сделать только с помощью кода.