WPF实现简单的文件浏览界面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kakaluote81/article/details/80341794

    使用WPF编写文件浏览界面,做的比较简单。因为没有找到合适的第三方库,所以自己手动写一个简单的先试试。没有使用XAML,纯C#代码实现。主要使用的控件Grid, TreeView, ListView,GridSplitter。

    使用了两个简单的文件夹图标,使用了Binding,(这个我也不是特别熟,但是勉强用上了),编写了几个简单的类。参考了网上的一些资料和书籍,先总结如下:


    01、ImagedTreeViewItem类,继承自TreeViewItem

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Media;

namespace LocalFileManager
{
    /// <summary>
    /// 简单的Item类,选中和不被选中用两种图标表示
    /// 内置一个StackPanel,包括一个TextBlock显示文本,图片
    /// </summary>
    public class ImagedTreeViewItem : TreeViewItem
    {
        TextBlock text;
        Image img;
        ImageSource srcSelected, srcUnselected;

        /// <summary>
        /// Constructor makes stack with image and text
        /// </summary>
        public ImagedTreeViewItem()
        {
            StackPanel stack = new StackPanel();
            stack.Orientation = Orientation.Horizontal;
            Header = stack;

            img = new Image();
            img.VerticalAlignment = VerticalAlignment.Center;
            img.Margin = new Thickness(0, 0, 2, 0);
            stack.Children.Add(img);

            text = new TextBlock();
            text.VerticalAlignment = VerticalAlignment.Center;
            stack.Children.Add(text);
        }

        /// <summary>
        /// Public porperty for text and images
        /// </summary>
        public string Text
        {
            get { return text.Text; }
            set { text.Text = value; }
        }

        public ImageSource SelectedImage
        {
            get { return srcSelected; }
            set
            {
                srcSelected = value;

                if(IsSelected)
                {
                    img.Source = srcSelected;
                }
            }//end of set
        }//end of public Imagesource SelectedItem

        public ImageSource UnselectedImage
        {
            get { return srcUnselected; }
            set
            {
                srcUnselected = value;
                if(!IsSelected)
                {
                    img.Source = srcUnselected;
                }
            }//end of set
        }//end of public ImageSource UnselectedImage

        /// <summary>
        /// Event override to set image
        /// </summary>
        /// <param name="e"></param>
        protected override void OnSelected(RoutedEventArgs e)
        {
            base.OnSelected(e);
            img.Source = srcSelected;
        }

        protected override void OnUnselected(RoutedEventArgs e)
        {
            base.OnUnselected(e);
            img.Source = srcUnselected;
        }
    }
}

    02、文件夹列表item,继承自ImagedTreeViewItem

using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace LocalFileManager
{
    /// <summary>
    /// 文件夹列表item,继承自ImagedTreeViewItem
    /// </summary>
    public class DirectoryTreeViewItem : ImagedTreeViewItem
    {
        DirectoryInfo dir;

        //Constructor requires DirectoryInfo object
        public DirectoryTreeViewItem(DirectoryInfo pDir)
        {
            this.dir = pDir;
            Text = pDir.Name;

            SelectedImage = new BitmapImage(new Uri("pack://application:,,/img/OPEN.BMP"));
            UnselectedImage = new BitmapImage(new Uri("pack://application:,,/img/CLOSED.BMP"));
        }

        /// <summary>
        /// public property to obtain DirectoryInfo
        /// </summary>
        public DirectoryInfo DirInfo
        {
            get { return dir; }
        }

        /// <summary>
        /// public mathod to populate wtih items
        /// </summary>
        public void Populate()
        {
            DirectoryInfo[] dirs;

            try
            {
                dirs = dir.GetDirectories();
            }
            catch
            {
                return;
            }

            foreach(DirectoryInfo dirChild in dirs)
            {
                Items.Add(new DirectoryTreeViewItem(dirChild));
            }
        }

        /// <summary>
        /// event override to populate subitem
        /// </summary>
        /// <param name="e"></param>
        protected override void OnExpanded(RoutedEventArgs e)
        {
            base.OnExpanded(e);

            foreach(object obj in Items)
            {
                DirectoryTreeViewItem item = obj as DirectoryTreeViewItem;
                item.Populate();
            }
        }
    }
}

    03、路径树,继承自TreeView

using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace LocalFileManager
{
    /// <summary>
    /// 路径树,继承自TreeView
    /// </summary>
    public class DirectoryTreeView : TreeView
    {
        /// <summary>
        /// Constructor builds
        /// </summary>
        public DirectoryTreeView()
        {
            RefreshTree();
        }

        public void RefreshTree()
        {
            BeginInit();
            Items.Clear();

            //Obtain the disk drivers
            DriveInfo[] drivers = DriveInfo.GetDrives();

            foreach(DriveInfo drive in drivers)
            {
                char chDrive = drive.Name.ToUpper()[0];
                DirectoryTreeViewItem item = new DirectoryTreeViewItem(drive.RootDirectory);

                //display ...
                if(chDrive != 'A' && chDrive != 'B' && drive.IsReady && drive.VolumeLabel.Length > 0)
                {
                    item.Text = string.Format("{0}  ({1})", drive.VolumeLabel, drive.Name);
                }
                else
                {
                    item.Text = string.Format("{0}  ({1})", drive.DriveType, drive.Name);
                }

                Items.Add(item);

                if(chDrive != 'A' && chDrive != 'B' && drive.IsReady)
                {
                    item.Populate();
                }
            }

            EndInit();
        }
    }
}

    04、文件信息类,自定义了几个需要显示的文件的属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LocalFileManager
{
    /// <summary>
    /// 自定义的文件信息类,用于绑定到ListViewItem中
    /// </summary>
    public class FileInfoDemo
    {
        string strFileName;
        string strFileType;
        string strFileSize;
        string _lastModifyTime;
        string _filePath;

        /// <summary>
        /// 文件名
        /// </summary>
        public string FileName
        {
            get { return strFileName; }
            set { strFileName = value; }
        }

        /// <summary>
        /// 文件类型
        /// </summary>
        public string FileType
        {
            get { return strFileType; }
            set { strFileType = value; }
        }

        /// <summary>
        /// 文件大小
        /// </summary>
        public string Size
        {
            get { return strFileSize; }
            set { strFileSize = value; }
        }

        /// <summary>
        /// 最后一次修改时间
        /// </summary>
        public string LastModifyTime
        {
            get { return _lastModifyTime; }
            set { _lastModifyTime = value; }
        }

        /// <summary>
        /// 文件所在路径
        /// </summary>
        public string FilePath
        {
            get { return _filePath; }
            set { _filePath = value; }
        }
    }
}

    05、主界面

 ListView lvFileInfo = new ListView();
        public LocalFileManager()
        {
            Title = "LocalFileManager";

            //网格布局
            Grid grid = new Grid();
            Content = grid;

            //定义3列
            ColumnDefinition coldef = new ColumnDefinition();
            coldef.Width = new GridLength(50, GridUnitType.Star);
            grid.ColumnDefinitions.Add(coldef);

            coldef = new ColumnDefinition();
            coldef.Width = GridLength.Auto;
            grid.ColumnDefinitions.Add(coldef);

            coldef = new ColumnDefinition();
            coldef.Width = new GridLength(50, GridUnitType.Star);
            grid.ColumnDefinitions.Add(coldef);

            //定义文件夹树
            DirectoryTreeView mainTree = new DirectoryTreeView();
            mainTree.SelectedItemChanged += MainTree_SelectedItemChanged;
            grid.Children.Add(mainTree);
            Grid.SetColumn(mainTree, 0);

            //分隔条
            GridSplitter splite = new GridSplitter();
            splite.Width = 6;
            splite.ResizeBehavior = GridResizeBehavior.PreviousAndNext;
            grid.Children.Add(splite);
            Grid.SetColumn(splite, 1);

            //全局ListView
            lvFileInfo = new ListView();
            grid.Children.Add(lvFileInfo);
            Grid.SetColumn(lvFileInfo, 2);


            //定义字段,绑定到文件信息类中
            GridView myview = new GridView();
            lvFileInfo.View = myview;
            GridViewColumn mycolun = new GridViewColumn();
            mycolun.Header = "文件名";
            mycolun.Width = 80;
            mycolun.DisplayMemberBinding = new Binding("FileName");
            myview.Columns.Add(mycolun);

            mycolun = new GridViewColumn();
            mycolun.Header = "类型";
            mycolun.Width = 80;
            mycolun.DisplayMemberBinding = new Binding("FileType");
            myview.Columns.Add(mycolun);

            mycolun = new GridViewColumn();
            mycolun.Header = "大小";
            mycolun.Width = 80;
            mycolun.DisplayMemberBinding = new Binding("Size");
            myview.Columns.Add(mycolun);

            mycolun = new GridViewColumn();
            mycolun.Header = "最后修改";
            mycolun.Width = 80;
            mycolun.DisplayMemberBinding = new Binding("LastModifyTime");
            myview.Columns.Add(mycolun);

            mycolun = new GridViewColumn();
            mycolun.Header = "路径";
            mycolun.Width = 80;
            mycolun.DisplayMemberBinding = new Binding("FilePath");
            myview.Columns.Add(mycolun);

            //右键菜单添加测试
            ContextMenu myContext = new ContextMenu();

            MenuItem myMUItem = new MenuItem();
            myMUItem.Header = "下载";
            myMUItem.Name = "Menu01";
            myContext.Items.Add(myMUItem);

            myMUItem = new MenuItem();
            myMUItem.Header = "查看";
            myMUItem.Name = "FileLook";
            myMUItem.Click += FileLook_Click;
            myContext.Items.Add(myMUItem);

            myMUItem = new MenuItem();
            myMUItem.Header = "刷新";
            myMUItem.Name = "Menu03";
            myContext.Items.Add(myMUItem);

            myMUItem = new MenuItem();
            myMUItem.Header = "重命名";
            myMUItem.Name = "Menu04";
            myContext.Items.Add(myMUItem);

            myMUItem = new MenuItem();
            myMUItem.Header = "新建文件夹";
            myMUItem.Name = "Menu05";
            myContext.Items.Add(myMUItem);

            lvFileInfo.ContextMenu = myContext;

        }

    06、当文件夹选择改变时,调用事件查找选择的文件夹下的文件,并显示到ListView中

 /// <summary>
        /// 文件夹树改变时,查找文件夹下是否存在文件,如果存在,则显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            DirectoryTreeViewItem item = e.NewValue as DirectoryTreeViewItem;

            //stack.Children.Clear();
            lvFileInfo.Items.Clear();

            FileInfo[] fileInfos;

            try
            {
                fileInfos = item.DirInfo.GetFiles();
            }
            catch
            {
                return;
            }

            foreach(FileInfo info in fileInfos)
            {
                FileInfoDemo myFile = new FileInfoDemo();
                myFile.FileName = info.Name;
                myFile.Size = info.Length.ToString();
                myFile.LastModifyTime = info.LastAccessTime.ToString();
                myFile.FilePath = info.DirectoryName;
                myFile.FileType = info.Extension;

                lvFileInfo.Items.Add(myFile);
            }
        }

    完成代码请见:https://download.csdn.net/download/kakaluote81/10418964


    水平有限,欢迎指正批评。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页