2015-04-23 83 views

回答

1

您可以編寫自己的轉換器,截斷給定最大長度的字符串

public class MaxStringConverter : IValueConverter 
{ 
    public MaxStringConverter() 
    { 
     ReplaceChars = "..."; 
     MaxLenght = int.MaxValue; 
    } 

    public int MaxLength { get; set; } 
    public string ReplaceChars { get; set; } 

    public object Convert(object value, Type targetType, object parameter, string culture) 
    { 
     string val = (string)value; 
     int replaceCharLength = ReplaceChars.Length; 
     if(val.Lenght > MaxLength) 
     { 
      int middle = val.Lenght/2; 
      int textLenth = MaxLength - 2 * replaceCharLength; 
      string textToReturn = val.Substring(middle - replaceCharLength , textLenth); 
      return string.Format("{1}{0}{1}", textToReturn, ReplaceChars); 
     } 
    } 
} 

然後用它作爲

<Window.Resources> 
    <MaxStringConverter x:Key="MaxStringConverter" MaxLength=100/> 
</Window.Resources> 

<TextBlock Text="{Binding Path=MyText, Converter={StaticResource MaxStringConverter}}"/> 
相關問題