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

效果

后端

cs 复制代码
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();
        }
    }
}

前端

引入

XML 复制代码
xmlns:local="clr-namespace:XXXX.ViewModel"
XML 复制代码
<local:ConvertBytesToSize x:Key="ConvertBytesToSize" />

使用

XML 复制代码
<TextBlock Grid.Row="1" Text="{Binding Path=AllSize,Converter='{StaticResource ConvertBytesToSize}', StringFormat='可节省{0}'}" FontSize="9"/>
相关推荐
dalong1021 小时前
WPF:3D正四面体旋转改错
3d·wpf
dalong102 天前
WPF:3D正四面体自动旋转
3d·wpf
He BianGu2 天前
【WPF-Control】二次开发总览
wpf
绿浪19842 天前
WPF 后台刷新界面总结
wpf
绿浪19843 天前
WPF UI标准流水线
ui·wpf
心平气和量大福大3 天前
C#-WPF-控件-LiveChart图表-线性2(LineSeries)-数据绑定
开发语言·c#·wpf
绿浪19843 天前
WPF 防重入,时序错乱详解
wpf
whn19774 天前
oracle的节点2无法启动asm实例 提示PMON terminating the instance due to error 481
数据库·oracle·wpf
完美火龙篇 四月的友4 天前
WPF 笔迹延迟优化从硬件到软件的全链路分析
wpf
dalong104 天前
WPF:3D立方体
3d·wpf