簡體   English   中英

WPF:是否可以從XAML調用函數

[英]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 sizebytesbytes ,我想將其轉換為人類可讀的格式,例如2.34MB1.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM