wpf 数据转换(Bytes 转 KB MB GB)

效果

 后端

using ProCleanTool.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;

namespace ProCleanTool.ViewModel
{
    internal class ConvertBytesToSize : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            long total = 0;
            if(value !=  null)
            {
                total = (long)value;    
            }
            return ConvertBytesToSizeFun(total);
        }
        public static string ConvertBytesToSizeFun(long bytes)
        {
            double size = (double)bytes;

            if (size < 1024) //小于等于1KB的情况
                return $"{size} B";

            else if (size >= 1024 && size <= Math.Pow(1024, 2)) //大于等于1KB且小于等于1MB的情况
                return $"{(size / 1024):F2} KB";

            else if (size > Math.Pow(1024, 2) && size <= Math.Pow(1024, 3)) //大于等于1MB且小于等于1GB的情况
                return $"{(size / Math.Pow(1024, 2)):F2} MB";

            else //大于等于1GB的情况
                return $"{(size / Math.Pow(1024, 3)):F2} GB";
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

前端

引入

xmlns:local="clr-namespace:XXXX.ViewModel"

 使用

你可能感兴趣的:(C#,wpf)