使用复选框创建WPF窗口资源管理器树状视图



我正在尝试创建一个带有复选框的WPF windows资源管理器树状视图文件浏览器,用于选择多个文件。复选框应仅针对文件进行查看。像这样在此处输入图像描述

我在WPF方面没有太多经验,这对我来说很难开始。

谢谢。

我将向您介绍如何实现它的最简单的想法。考虑两个类FolderFile(为了简化示例,我已经实现了自己的简单类(:

public class Folder
{
public List<Folder> Folders { get; set; } = new();
public List<File> Files { get; set; } = new();

public override string ToString() => Name;
public string Name { get; set; }
}
public class File
{
public string Name { get; set; }

public override string ToString() => Name;
}

你会有这样的MultiselectTreeView实现:

public class MultiSelectTree: TreeView
{
public List<File> SelectedFiles { get; set; } = new();

public void AddItem(object item)
{
if (item is Folder folder)
{
var root = FormFolderTreeItem(folder);
Items.Add(root);
}
if (item is File file)
{
var f = FormFileTreeItem(file);
Items.Add(f);
}
}
private TreeViewItem FormFolderTreeItem(Folder folder)
{
var treeItem = new TreeViewItem { Header = folder };
foreach (var subFolderItem in folder.Folders.Select(FormFolderTreeItem))
{
treeItem.Items.Add(subFolderItem);
}
foreach (var file in folder.Files.Select(FormFileTreeItem))
{
treeItem.Items.Add(file);
}

return treeItem;
}

private TreeViewItem FormFileTreeItem(File file)
{
var treeItem = new TreeViewItem ();
// wrap Files in a checkbox and set this checkbox as a content of a TreeViewItem
var checkBox = new CheckBox { Content = file };
treeItem.Header = checkBox;

// Subscribe for the checked event
// When the event triggers - add file to the SelectedFiles
checkBox.Checked += (sender, args) =>
{
if (sender is CheckBox chb)
{
SelectedFiles.Add((File)chb.Content);
}
args.Handled = true;
};

// Just the opposite here
checkBox.Unchecked += (sender, args) =>
{
if (sender is CheckBox chb)
{
SelectedFiles.Remove((File)chb.Content);
}
args.Handled = true;
};
return treeItem;
}
}

然后,您可以访问具有SelectedFiles属性的选定文件。

以下是用法示例(Tree是MultiSelectTree的实例(:

var firstRoot = new Folder { Name = "Root" };
var secondRoot = new Folder {Name = "Second Root"};

firstRoot.Folders.Add(new Folder { Name = "Sub folder"});

secondRoot.Files.AddRange(new []
{
new File {Name = "First file" },
new File {Name = "Second file" }
});

Tree.AddItem(firstRoot);
Tree.AddItem(secondRoot);

因此,你会有这样的结果:带复选框的TreeView和多选

现在,您必须弄清楚如何调整您在设计WPF树视图文件浏览器中已经使用的示例

相关内容

  • 没有找到相关文章

最新更新