c# 项目 文件夹

c#专栏记录:



前言

日常项目记录,看的b站某up主的啦

项目介绍:实现 文件树

App.xaml

c# 复制代码
<Application x:Class="Wpf_desktop.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:Wpf_desktop"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
         
    </Application.Resources>
</Application>

AssemblyInfo.cs

c# 复制代码
using System.Windows;

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None,            //where theme specific resource dictionaries are located
                                                //(used if a resource is not found in the page,
                                                // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly   //where the generic resource dictionary is located
                                                //(used if a resource is not found in the page,
                                                // app, or any theme specific resource dictionaries)
)]

HeaderToImageConverter.cs

csharp 复制代码
using System;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Wpf_desktop
{
    //converts a full path to a specific image type of a drive, folder oe file
    [ValueConversion(typeof(string), typeof(BitmapImage))]

    public class HeaderToImageConverter: IValueConverter
    {
        public static HeaderToImageConverter Instance = new HeaderToImageConverter();
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            //get the file name
            var path = (string)value;



            //get the name of the file
            var name = MainWindow.GetFileFolderName(path);
            //by default ,we presume an image
            var image = "/Image/open-folder.png";

            //IF the name is blank , we presume it's a drive as
            if(string.IsNullOrEmpty(name))
                image = "/Image/gary-folder.png";
            else if (new FileInfo(path).Attributes.HasFlag(FileAttributes.Directory))
                image = "/Image/folder.png";

            return new BitmapImage(new Uri($"C:/Users/Administrator/source/repos/Wpf_desktop{image}"));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

MainWindow.xaml

csharp 复制代码
<Window x:Class="Wpf_desktop.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Wpf_desktop"
        Loaded="Window_Loaded"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>


        <TreeView x:Name="FolderView">
            <TreeView.Resources>
                <Style TargetType="{x:Type TreeViewItem}"> 
                    <Setter Property="HeaderTemplate" >
                        <Setter.Value>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <Image Width="20" Margin="2" 
                                           Source="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type TreeViewItem}},
                                        Path=Tag,
                                        Converter={x:Static local:HeaderToImageConverter.Instance}}"/>
                                    <TextBlock VerticalAlignment="Center" FontStyle="Normal" Text="{Binding}"></TextBlock>
                                </StackPanel>
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TreeView.Resources>
        </TreeView>
    </StackPanel>
</Window>

MainWindow.xaml.cs

csharp 复制代码
using System.Collections.Generic;
using System.IO;
using System.Reflection.PortableExecutable;
using System.Windows;
using System.Windows.Controls;
namespace Wpf_desktop
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Constructor

        /// <summary>
        /// Default constructor
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
        }

        #endregion

        #region On Loaded

        /// <summary>
        /// When the application first opens
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Get every logical drive on the machine
            foreach (var drive in Directory.GetLogicalDrives())
            {
                // Create a new item for it
                var item = new TreeViewItem()
                {
                    // Set the header
                    Header = drive,
                    // And the full path
                    Tag = drive
                };

                // Add a dummy item
                item.Items.Add(null);

                // Listen out for item being expanded
                item.Expanded += Folder_Expanded;

                // Add it to the main tree-view
                FolderView.Items.Add(item);
            }
        }

        #endregion

        #region Folder Expanded

        /// <summary>
        /// When a folder is expanded, find the sub folders/files
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Folder_Expanded(object sender, RoutedEventArgs e)
        {
            #region Initial Checks

            var item = (TreeViewItem)sender;

            // If the item only contains the dummy data
            if (item.Items.Count != 1 || item.Items[0] != null)
                return;

            // Clear dummy data
            item.Items.Clear();

            // Get full path
            var fullPath = (string)item.Tag;

            #endregion

            #region Get Folders

            // Create a blank list for directories
            var directories = new List<string>();

            // Try and get directories from the folder
            // ignoring any issues doing so
            try
            {
                var dirs = Directory.GetDirectories(fullPath);

                if (dirs.Length > 0)
                    directories.AddRange(dirs);
            }
            catch { }

            // For each directory...
            directories.ForEach(directoryPath =>
            {
                // Create directory item
                var subItem = new TreeViewItem()
                {
                    // Set header as folder name
                    Header = GetFileFolderName(directoryPath),
                    // And tag as full path
                    Tag = directoryPath
                };

                // Add dummy item so we can expand folder
                subItem.Items.Add(null);

                // Handle expanding
                subItem.Expanded += Folder_Expanded;

                // Add this item to the parent
                item.Items.Add(subItem);
            });

            #endregion

            #region Get Files

            //create a blank list for folders
            var files = new List<string>();

            //Try and get files from the folder ignoring any issues doing so
            try
            {
                var fs = Directory.GetFiles(fullPath);
                if (fs.Length > 0)
                    files.AddRange(fs);
            }
            catch { }
            // for each file..
            files.ForEach(filePath =>
            {
                var subItem = new TreeViewItem()
                {
                    //set header as file name
                    Header = GetFileFolderName(filePath),
                    Tag = filePath
                };
                item.Items.Add(subItem);
            });


            
        }

        #endregion

        #region Helpers
        public static string GetFileFolderName(string path)
        { 
            if (string.IsNullOrEmpty(path))
                return string.Empty;
            //make all slashes bace slashes
            var normalizedPath = path.Replace('/', '\\');
            //Find the last backslash in the path
            var lastIndex = normalizedPath.LastIndexOf('\\');
            //if WE DON'T find a backslash, return the path itsets
            if (lastIndex <= 0)
                return path;
            //return the name after the last backslash
            return path.Substring(lastIndex + 1);
        }
        #endregion
    }
    #endregion
}

知识内容

WPF

TreeView 文件视图


总结

阿巴阿巴!!!!


致谢

靠咖啡续命的牛马,👍点赞 📁 关注 💬评论 💰打赏。


参考

1\] deepseek等ai


往期回顾

  • 无,新手上车
相关推荐
牛角上的男孩2 小时前
apt update Ign and 404 Not Found
开发语言·数据库
yzzzzzzzzzzzzzzzzz3 小时前
JavaScript 操作 DOM
开发语言·javascript·ecmascript
小白要加油努力5 小时前
C++设计模式--策略模式与观察者模式
开发语言·c++·设计模式
小马学嵌入式~5 小时前
数据结构:队列 二叉树
c语言·开发语言·数据结构·算法
Slaughter信仰6 小时前
深入理解Java虚拟机:JVM高级特性与最佳实践(第3版)第二章知识点问答(21题)
java·开发语言·jvm
曹牧7 小时前
C#:窗体间传值
c#
焊锡与代码齐飞7 小时前
嵌入式第三十五课!!Linux下的网络编程
linux·运维·服务器·开发语言·网络·学习·算法
KeithTsui8 小时前
GCC C语言整数转换的理解(Understanding of Integer Conversions in C with GCC)
c语言·开发语言·算法
秉承初心8 小时前
Node.js 开发 JavaScript SDK 包的完整指南(AI)
开发语言·javascript·node.js