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"/>
相关推荐
ou.cs1 天前
wpf 队列(Queue)在视觉树迭代查找中的作用分析
wpf
code bean1 天前
【WPF】WPF 中 `DisplayMemberPath` 与 `SelectedValuePath` 的深入理解与实战应用
windows·wpf
Magnum Lehar2 天前
wpf3d游戏引擎EditorColors.xaml实现
ui·游戏引擎·wpf
ou.cs2 天前
wpf 解决DataGridTemplateColumn中width绑定失效问题
c#·wpf
Magnum Lehar3 天前
wpf3d游戏引擎ControlTemplate.xaml.cs文件实现
游戏引擎·wpf
Magnum Lehar3 天前
wpf游戏引擎前端的Transform.cs实现
前端·游戏引擎·wpf
@Crazy Snail3 天前
WPF数据绑定疑惑解答--(关于控件的Itemsource,Collection绑定)
windows·wpf·wpf数据绑定
猕员桃3 天前
《Elasticsearch 分布式搜索在聊天记录检索中的深度优化》
分布式·elasticsearch·wpf
Magnum Lehar3 天前
wpf3d游戏引擎前端ControlTemplate实现
前端·游戏引擎·wpf
天蓝蓝的本我4 天前
WPF加载文本文件时如何设置WebBrowser的字体
wpf