效果
后端
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"/>