本文主要是介绍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"/>
这篇关于wpf 数据转换(Bytes 转 KB MB GB)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!