[英]WPF: is it possible to call function from XAML
所以我有這個Calss Member
計算我的實際文件大小:
private static ulong _fileSize;
public static ulong FileSize
{
get { return _fileSize; }
set
{
_fileSize = value;
OnPropertyChanged();
}
}
我的類實現了INotifyPropertyChanged
。
XAML
然后我的UI
會自動更新:
<Label
Content="{Binding Path=(my:MyClass.FileSize)}"
ContentStringFormat="{}{0:0.##}"/>
但是我的問題是我的file size
以bytes
為bytes
,我想將其轉換為人類可讀的格式,例如2.34MB
或1.01 GB
因此我具有以下功能:
static string SizeSuffix(ulong buyes, int decimalPlaces = 0)
{
string[] SizeSuffixes = { "bytes", "KB", "MB", "GB" };
if (buyes > 0)
{
var mag = (int)Math.Max(0, Math.Log(buyes, 1024));
var adjustedSize = Math.Round(buyes / Math.Pow(1024, mag), decimalPlaces);
return String.Format("{0} {1}", adjustedSize, SizeSuffixes[mag]);
}
else
return "0";
}
所以我的問題是:是否可以從XAML
調用SizeSuffix
函數?
可以使用Converter來使用您的convert函數將原始文件大小的字節轉換為所需的字符串,但這可能是更好的方法來顯示具有此(轉換)值的屬性。
在這種情況下,在視圖模型(數據上下文)中創建另一個屬性會很有用,它將轉換為人類可讀的文件大小,因為這是一個只讀屬性,可以在模型中進行更新。
碼:
private static ulong _fileSize;
private string _fileSizeString;
public static ulong FileSize
{
get { return _fileSize; }
set
{
_fileSize = value;
OnPropertyChanged("FileSize");
OnPropertyChanged("FileSizeString");
}
}
public string FileSizeString { get { return SizeSuffix(FileSize); }}
然后,在xaml中,只需將標簽綁定到FileSizeString屬性即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.