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"
<local:ConvertBytesToSize x:Key="ConvertBytesToSize" />

 使用

<TextBlock Grid.Row="1" Text="{Binding Path=AllSize,Converter='{StaticResource ConvertBytesToSize}', StringFormat='可节省{0}'}" FontSize="9"/>

相关推荐

  1. C++ hexuint,uint 互相转换,uintbyte

    2024-01-30 09:18:01       41 阅读
  2. WPF-C# byte[]ImageSource常用方法

    2024-01-30 09:18:01       32 阅读
  3. int和byte数组相互转换详解

    2024-01-30 09:18:01       37 阅读
  4. C# 从“byte[]”转换为“BitmapImage”

    2024-01-30 09:18:01       57 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-30 09:18:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-30 09:18:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-30 09:18:01       82 阅读
  4. Python语言-面向对象

    2024-01-30 09:18:01       91 阅读

热门阅读

  1. 使用Redis LIst 实现数据库分页快速查询的方法

    2024-01-30 09:18:01       54 阅读
  2. C Primer Plus(第六版)14.18 编程练习 第5题

    2024-01-30 09:18:01       50 阅读
  3. 代码随想录算法训练营|day20

    2024-01-30 09:18:01       66 阅读
  4. C#设置程序开机启动

    2024-01-30 09:18:01       56 阅读
  5. 基于 MATLAB 语言的 BP 神经网络的改进算法

    2024-01-30 09:18:01       53 阅读
  6. 力扣面试题02.07-链表相交

    2024-01-30 09:18:01       59 阅读
  7. gorm框架之常用增删改查(CRUD)

    2024-01-30 09:18:01       55 阅读
  8. 如何多个excel中的数据分发到多个excel中去

    2024-01-30 09:18:01       43 阅读
  9. 每日OJ题_算法_前缀和⑤_力扣560. 和为 K 的子数组

    2024-01-30 09:18:01       63 阅读
  10. TensorFlow2实战-系列教程8:TFRecords数据源制作2

    2024-01-30 09:18:01       71 阅读