如何为字符串的长度设置StringFormat

时间:2012-11-29 15:12:20

标签: xaml string-formatting

所以我知道可以在Binding中为StringFormat和数值设置StringFormat,但我想要实现的是StringFormat,其中包含以下字符串:

“这是一个长文本的主体,在数据库中定义为varchar(max)。这意味着字符串很长。”

“这是长文本的主体......”(最大长度为25个字符)

提前致谢

1 个答案:

答案 0 :(得分:1)

使用值转换器:

  public class LongtoShortenedStringValueConverter : IValueConverter
{
    private const int MaxLength= 0D;

    /// <summary>
    /// Modifies the source data before passing it to the target for display
    /// in the UI.
    /// </summary>
    /// <returns>
    /// The value to be passed to the target dependency property.
    /// </returns>
    /// <param name="value">
    /// The source data being passed to the target.
    /// </param>
    /// <param name="targetType">
    /// The <see cref="T:System.Type"/> of data expected by the target
    /// dependency property.
    /// </param>
    /// <param name="parameter">
    /// An optional parameter to be used in the converter logic.
    /// </param>
    /// <param name="culture">The culture of the conversion.</param>
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
        {
            return string.Empty;
        }

         return string.Concat(longString.Substring(0, MaxLength), "...");
    }

    /// <summary>
    /// Modifies the target data before passing it to the source object. This
    /// method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/>
    /// bindings.
    /// </summary>
    /// <returns>
    /// The value to be passed to the source object.
    /// </returns>
    /// <param name="value">The target data being passed to the source.</param>
    /// <param name="targetType">
    /// The <see cref="T:System.Type"/> of data expected by the source object.
    /// </param>
    /// <param name="parameter">
    /// An optional parameter to be used in the converter logic.
    /// </param>
    /// <param name="culture">The culture of the conversion.</param>
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

}

所以上面会根据常量值将oit修剪为80个字符。然后在你的xaml绑定到字段

Text="{Binding YourLongString, Converter={StaticResource LongToShortStringValueConverter}}"