vue-java-tutorials/CSharp/WPFTutorial/WPF-25-TreeView/Convert/HeaderToImageConverter.cs

40 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
namespace WPF_25_TreeView.Convert;
[ValueConversion(typeof(string), typeof(BitmapImage))]
public class HeaderToImageConverter : IValueConverter
{
public static readonly HeaderToImageConverter Instance = new();
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
{
var path = (string)value!;
if (string.IsNullOrEmpty(path)) return null;
// 判断是否是文件夹
// // 方法1直接使用 Directory.Exists推荐大多数情况
// var isDirectory = Directory.Exists(path);
// // 方法2检查文件属性处理符号链接等特殊情况
// var isDirectory = File.GetAttributes(path).HasFlag(FileAttributes.Directory);
var isDirectory = Directory.Exists(path) ||
(File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory;
var extension = Path.GetExtension(path).ToLower();
var image = isDirectory ? "Assets/folder.png" :
extension is ".jpg" or ".jpeg" ? "Assets/jpg.png" :
extension is ".java" ? "Assets/code.ico" :
extension is ".ogg" ? "Assets/ogg.ico" :
"Assets/file.png";
return new BitmapImage(new Uri($"pack://application:,,,/{image}"));
}
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
{
return new object();
}
}