背景:
写了一个CS工具,想在客户端打开一个文件夹浏览窗口显示服务器端的文件夹。
问题:
对现成的FolderBrowserDialog不知怎么应用到这种场景,只好自己写一个简陋的窗口。服务器端用的WCF,想着由服务器端传XML到客户端,用TreeView在客户端显示。
代码:
XAML:
<Window x:Class="WpfApplication1.MyFolderBrowserWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="浏览服务器文件夹" Height="300" Width="300" ResizeMode="NoResize" WindowStartupLocation="CenterOwner"> <Window.Resources> <HierarchicalDataTemplate x:Key="ItemTemplate" ItemsSource="{Binding XPath=Folder}"> <TextBlock Text="{Binding [email protected]}"/> </HierarchicalDataTemplate> </Window.Resources> <Grid> <TreeView Name="TreeView" ItemsSource="{Binding}" TreeViewItem.Expanded="TreeView_Expanded"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding XPath=Folder}"> <StackPanel Orientation="Horizontal" Margin="2"> <Image Source="folder2.png" Width="16" Height="16" SnapsToDevicePixels="True"/> <TextBlock Text="{Binding [email protected]}" Margin="5,0"/> </StackPanel> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </Grid> </Window>
C#:
打开窗口之前,服务器端会首先一个字符串,包括服务器名称和System.IO.DriveInfo.GetDrives()组成的XML。然后每次展开一个层级的时候,触发事件获得下一个层级的子文件夹列表。(为了有那个三角。。。)
public partial class MyFolderBrowserWindow : Window { //字符串格式:<Folder Name=\"ServerName\"><Folder Name=\"C:\" FullPath=\"C:\\\"></Folder></Folder> public string RootFolders { get; set; } public MyFolderBrowserWindow() { InitializeComponent(); this.Loaded += Window2_Loaded; } void Window2_Loaded(object sender, RoutedEventArgs e) { XmlDataProvider xdp = new XmlDataProvider(); xdp.XPath = "Folder"; XmlDocument xd = new XmlDocument(); xd.LoadXml(RootFolders); xdp.Document = xd; this.TreeView.Items.Clear();//Items和ItemSource,只能有一个生效,想用其中一个,另一个必须是空, but why items is not empty? this.TreeView.DataContext = xdp; } private void TreeView_Expanded(object sender, RoutedEventArgs e) { TreeViewItem item = e.OriginalSource as TreeViewItem; if(item != null) { if(item.HasItems) { foreach (var childitem in item.Items) { XmlElement element = childitem as XmlElement; if(!element.HasChildNodes) { string fullPath = element.GetAttribute("FullPath"); element.InnerXml = GetChildFolders(fullPath);//"<Folder Name=\"WPF\"/><Folder Name=\"MFC\"/><Folder Name=\"Delphi\"/>"; } } } } } public event Func<string, string> GetChildFoldersEvent; public delegate string GetChildFoldersEventHandler(object sender, FolderEventArgs args); public event GetChildFoldersEventHandler GetChildFoldersEvent2; private string GetChildFolders(string fullPath) { FolderEventArgs args = new FolderEventArgs(); args.FullPath = fullPath; return GetChildFoldersEvent2(this, args); //return GetChildFoldersEvent(fullPath); } } public class FolderEventArgs : EventArgs { public string FullPath { get; set; } }
结果:
参考:
http://www.cnblogs.com/bray/archive/2010/04/13/1711333.html
http://blog.csdn.net/easybjy/article/details/44338515
PS:如果有更简便的方法,请告之,万分感谢!(自己写好麻烦。。。)
时间: 2024-10-24 18:09:00