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

Xaml 如何为字符串的长度设置StringFormat,xaml,string-formatting,Xaml,String Formatting,因此,我知道可以在绑定中为日期和数值设置StringFormat,但我希望实现的是StringFormat,其中包含以下字符串: “这是在数据库中定义为varchar(max)的长文本的正文。这意味着字符串非常长。” 到 “这是长文本的正文…”(最大长度为25个字符) 提前感谢使用值转换器: public class LongtoShortenedStringValueConverter : IValueConverter { private const int MaxLength=

因此,我知道可以在绑定中为日期和数值设置StringFormat,但我希望实现的是StringFormat,其中包含以下字符串:

“这是在数据库中定义为varchar(max)的长文本的正文。这意味着字符串非常长。”

“这是长文本的正文…”(最大长度为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();
    }
}

我知道这是可能的,但我更喜欢搜索StringFormat,因为这对我来说“更容易”。这当然会解决我的问题,另一种方法是在视图模型上使用一个属性,它是LongFieldDisplayText,基本上只是原始值的包装器,但返回的格式如您所愿。出于某种原因,有些人似乎对在viewmodel中放置这样的东西感到不快,但我认为这没关系。正如Josh Smith在他的mvvm文章-viewmodel允许您删除转换器,因为它实际上是SteriodS上的转换器正如您所说,我创建了第二个字段来对付thius,感谢您提供的解决方案
Text="{Binding YourLongString, Converter={StaticResource LongToShortStringValueConverter}}"