我正在尝试将我的旧源代码更新为 UWP,引用 Microsoft.UI.Xaml.dll TreeView 控件以显示/复制存储在字符串 [] 中的文件和文件夹。
string[] 存储一个或多个文件的完整路径。
例子:
C:\Users\User\Documents\Test1.txt
C:\Users\User\Documents\Test2.txt
C:\用户\用户\文档\文件夹\Test1.txt
C:\用户\用户\文档\文件夹\Test2.txt
我想更新的代码如下:
private void PopulateTreeView(TreeView treeView, string[] paths, char pathSeparator)
{
TreeNode lastNode = null;
string subPathAgg;
long count = 0;
foreach (string path in paths)
{
subPathAgg = string.Empty;
foreach (string subPath in path.Split(pathSeparator))
{
Application.DoEvents();
subPathAgg += subPath + pathSeparator;
TreeNode[] nodes = treeView.Nodes.Find(subPathAgg, true);
if (nodes.Length == 0)
{
if (lastNode == null)
{
lastNode = treeView.Nodes.Add(subPathAgg, subPath);
}
else
{
lastNode = lastNode.Nodes.Add(subPathAgg, subPath);
}
count++;
}
else
{
lastNode = nodes[0];
}
}
lastNode = null; // This is the place code was changed
}
}
有谁知道如何使用 Microsoft.UI.Xaml.dll TreeView 控件更新此代码?我认为这应该很容易,但我觉得我错过了一些东西。
您的代码应该是 WPF 或 WinForm。该TreeView
在UWP有很多比他们的变化。如果你想从头开始处理这个控件,你可以查看这个文档。
现在让我们看一下代码。如果您打算TreeView
通过路径字符串创建一个,则在 UWP 中会更复杂。
public class PathDisplay
{
public string DisplayText { get; set; }
public string Path { get; set; }
public PathDisplay(){ }
public PathDisplay(string d, string p)
{
DisplayText = d;
Path = p;
}
public override string ToString()
{
return DisplayText;
}
}
subPathAgg
(该Find
方法在 中不再可用TreeView
)private IEnumerable<TreeViewNode> GetSameNodes(IList<TreeViewNode> nodes, string path)
{
foreach (var node in nodes)
{
var content = node.Content as PathDisplay;
if (content?.Path == path)
{
yield return node;
}
else
{
if (node.Children.Count > 0)
{
foreach (var item in GetSameNodes(node.Children,path))
{
yield return item;
}
}
}
}
}
PopulateTreeView
方法。在 UWP 中,许多类名和方法都发生了变化。private void PopulateTreeView(TreeView treeView, string[] paths, char pathSeparator)
{
TreeViewNode lastNode = null;
string subPathAgg;
long count = 0;
foreach (string path in paths)
{
subPathAgg = string.Empty;
foreach (string subPath in path.Split(pathSeparator))
{
subPathAgg += subPath + pathSeparator;
var displayModel = new PathDisplay(subPath, subPathAgg);
TreeViewNode[] nodes = GetSameNodes(treeView.RootNodes,subPathAgg).ToArray();
if (nodes.Length == 0)
{
if (lastNode == null)
{
lastNode = new TreeViewNode() { Content = displayModel };
treeView.RootNodes.Add(lastNode);
}
else
{
var node = new TreeViewNode() { Content = displayModel };
lastNode.Children.Add(node);
lastNode = node;
}
count++;
}
else
{
lastNode = nodes[0];
}
}
lastNode = null; // This is the place code was changed
}
}
这样我们就可以使用它
xml
<controls:TreeView x:Name="TestTreeView"
/>
xml文件
public TreeViewPage()
{
this.InitializeComponent();
PopulateTreeView(TestTreeView, new string[]{
@"C:\Users\User\Documents\Test1.txt",
@"C:\Users\User\Documents\Test2.txt",
@"C:\Users\User\Documents\folder\Test1.txt"
}, '\\');
}
它看起来像这样:
代码可以这样改写,但是我推荐文档中的集合绑定,更利于后期维护。
最好的祝福。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句