2014-07-26 126 views
6

我試圖格式化我的string每3個逗號就有一個逗號,如果它不是一個整數,則爲小數。我已經檢查大約20的例子,這是我來最接近:XAML中的StringFormat

<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" /> 

但我得到一個The property 'StringFormat' was not found in type 'Binding'.錯誤。

任何想法這裏有什麼錯? Windows Phone 8.1似乎與WPF不同,因爲所有的WPF資源都表示這是如何完成的。

(該string是不斷更新的,所以我需要的代碼是在XAML。我還需要它來保持綁定。當然,除非我不能讓我的蛋糕和熊掌兼得。)

+0

可能重複http://stackoverflow.com/questions/24127262/windows-phone-8- 1- XAML-的StringFormat) – Romasz

回答

10

似乎與WinRT中的Binding類似,Windows Phone Universal Apps中的Binding不具有StringFormat屬性。要解決此限制的一種可能的方式是使用Converterthis blog post解釋,

總結後,你可以創建一個IValueConverter implmentation接受字符串格式作爲參數:

public sealed class StringFormatConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, string language) 
    { 
     if (value == null) 
      return null; 

     if (parameter == null) 
      return value; 

     return string.Format((string)parameter, value); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, 
     string language) 
    { 
     throw new NotImplementedException(); 
    } 
} 

創建的上述資源在您的XAML轉換器,那麼你可以使用像這樣的例子:

<TextBlock x:Name="countTextBlock" 
      Text="{Binding Count, 
          Converter={StaticResource StringFormatConverter}, 
          ConverterParameter='{}{0:n}'}" /> 
[Windows Phone的8.1 ​​XAML的StringFormat(的
相關問題