所以我知道可以在 Binding 中为日期和数值设置 StringFormat,但我想要实现的是 StringFormat,其中包含以下字符串:
“这是一个长文本的正文,在数据库中定义为 varchar(max)。这意味着字符串很长。”
至
“这是一个长 tex 的正文......”(最大长度为 25 个字符)
提前致谢
所以我知道可以在 Binding 中为日期和数值设置 StringFormat,但我想要实现的是 StringFormat,其中包含以下字符串:
“这是一个长文本的正文,在数据库中定义为 varchar(max)。这意味着字符串很长。”
至
“这是一个长 tex 的正文......”(最大长度为 25 个字符)
提前致谢
使用值转换器:
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}}"