2010-01-05 140 views

回答

13

您可以使用值轉換器返回一個字符串前綴:

class PrefixValueConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     string s = value.ToString(); 
     int prefixLength; 
     if (!int.TryParse(parameter.ToString(), out prefixLength) || 
      s.Length <= prefixLength) 
     { 
      return s; 
     } 
     return s.Substring(0, prefixLength); 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     throw new NotSupportedException(); 
    } 
} 

並且在XAML中:

<Window.Resources> 
    ... 
    <local:PrefixValueConverter x:Key="PrefixValueConverter"/> 
</Window.Resources> 
... 
...{Binding Path=TheProperty, Converter={StaticResource PrefixValueConverter}, 
           ConverterParameter=1}... 
+1

而不是在ConvertBack中拋出'NotImplementedException',拋出'NotSupportedException'。 NIE用於尚未實施但即將推出的代碼。這裏:http://stackoverflow.com/questions/410719/notimplementedexception-are-they-kidding-me – 2010-01-05 13:15:34

+0

TBH,它實際上還沒有實施,採取您的建議,它現在是:) – 2010-01-05 13:43:41

+0

是的..謝謝Aviad,實際上我正在尋找避免使用converter.But似乎沒有辦法... thx – biju 2010-01-07 18:25:47

相關問題