2012-11-20 36 views
0

只是在數據綁定時遇到了格式化顯示字符串的問題。XAML數據綁定和動態字符串格式

假設我有一個屬性Size:

/// <summary> 
    /// Size information 
    /// </summary> 
    private long _size; 
    public long Size 
    { 
     get 
     { 
      return _size; 
     } 
     set 
     { 
      if (value != _size) 
      { 
       _size = value; 
       NotifyPropertyChanged("Size"); 
      } 
     } 
    } 

而這個大小是表示字節數的整數。我想顯示一個代表大小的值,取決於整數的大小。例如:

Size = 1 byte 
Size = 1 kilobyte 
Size = 100 megabytes 

這裏是我的TextBlock的XAML:

<TextBlock Text="{Binding Size, StringFormat='Size: {0}'}" TextWrapping="Wrap" Margin="12,110,0,0" Style="{StaticResource PhoneTextSubtleStyle}" Visibility="{Binding Visible}" FontSize="14" Height="20" VerticalAlignment="Top" HorizontalAlignment="Left" Width="200"/> 

截至目前它只是顯示「尺寸:50」,意思是50個字節,但我想讓它顯示「尺寸: 50字節/千字節/兆字節「(以適當的一個爲準),否則我會得到」大小:50000000000000「以及這樣的巨大數字。

我該如何去'動態'改變stringformat?

請記住,文本塊被封裝在一個由ObservableCollection界定的LongListSelector中,所以只需獲取文本塊並更改文本將不起作用,因爲如果您知道我的意思,將會有堆對象使用文本塊的格式。

謝謝。

回答

0

就我而言,我用了一點黑客。我將視圖綁定到一個viewModel,它包含一個包含格式化值的附加字符串屬性。例如,像這樣:

//using short scale: http://en.wikipedia.org/wiki/Long_and_short_scales#Comparison 
const decimal HundredThousand = 100 * 1000; 
const decimal Million = HundredThousand * 10; 
const decimal Billion = Million * 1000; //short scale 
const decimal Trillion = Billion * 1000; //short scale 

const string NumberFormatKilo = "{0:##,#,.## K;- ##,#,.## K;0}"; 
const string NumberFormatMillion = "{0:##,#,,.## M;- ##,#,,.## M;0}"; 
const string NumberFormatBillion = "{0:##,#,,,.## B;- ##,#,,,.## B;0}"; 
const string NumberFormatTrillion = "{0:##,#,,,,.## T;- ##,#,,,,.## T;0}"; 

public decimal Size 
{ 
    get; set; 
} 

public string SizeFormatted 
{ 
    get 
    { 
     var format = GetUpdatedNumberFormat(Size); 
     return string.Format(format, Size); 
    } 
} 

private static string GetUpdatedNumberFormat(decimal value) 
{ 
    string format = NumberFormat; 
    if (Math.Abs(value) >= Constants.Trillion) 
     format = NumberFormatTrillion; 
    else if (Math.Abs(value) >= Constants.Billion) 
     format = NumberFormatBillion; 
    else if (Math.Abs(value) >= Constants.Million) 
     format = NumberFormatMillion; 
    else if (Math.Abs(value) >= Constants.HundredThousand) 
     format = NumberFormatKilo; 
    return format; 
} 

現在,視圖綁定到該SizeFormatted屬性:

<TextBlock Text="{Binding SizeFormatted}" ... 
+0

正是我一直在尋找。我有一個類似的想法,其中Size的屬性將返回格式正確的字符串,但由於返回類型並將我的數據轉換爲正確的類型而導致一些問題,而不是。 謝謝! – Travv92

+0

很高興能幫到你!歡呼聲 – Krishna

+1

你應該使用一個轉換器。 – bleepzter