【问题标题】:WPF Custom TextTrimmingWPF 自定义 TextTrimming
【发布时间】:2013-04-11 04:12:11
【问题描述】:

我需要做一个特殊的文本修剪。假设我的字符串是:abcd

默认修剪会给我这个:ab...

但我需要它。 a..d

知道如何实现它吗?

目前我正在使用

<TextBlock Text="abcdLongWord" TextTrimming="CharacterEllipsis"/>

【问题讨论】:

  • 文本被修剪的标准是什么?您只想要第一个或最后一个字符?
  • ZombieHunter - 我希望显示的字符数是可配置的,但为了简化我们可以只从一个字符开始
  • 我发现了这样一个功能:vt-studio.co.uk/wp/?p=32
  • 您的问题中使用 XML 的目的是什么?您要修剪的字符串只是一个简单的字符串,对吗?如“如果字符串长于 X,则仅显示第一个和最后一个字母”,我正确吗?

标签: c# .net wpf trim


【解决方案1】:

我过去曾有过这种担忧,并编写了自己的转换器来处理 Kearning 的过程。

转换器类

internal class KearningConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        string result = value.ToString();

        try {
            int length = int.Parse(parameter.ToString());

            if (result.Length > length) {
                result = result.Substring(0, length) + "...";
            }
        } catch {
            result += "...";
        }
        return result;
    }

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

Xaml 标记

xmlns:conv="clr-namespace:project.converters;assembly=project"

<Window.Resources>
<conv:KearningConverter x:Key="kearnConverter"/>
</Window.Resources>

<TextBlock Text="{Binding Path=AttributeName, Converter={StaticResource kearnConverter}, ConverterParameter=3}"/>

通过这种方式,您可以根据 UI 布局的不同要求,对 Kearning 进行多种实现。

【讨论】:

  • 现在有趣的部分是动态计算 ConverterParameter 值。如果 TextBlock 的大小改变了怎么办?在这种情况下我们也应该修剪,不是吗?
【解决方案2】:

未对此进行测试,但取决于您的实际需要:

string test = "abcdefghij";
  int nCharNum = test.Length();
  test.Remove(2, nCharNum - 1); // this will get you "aj"
  //or
  test.Remove(2, 3); // this will result in "adefg..."
  //or
  test.Remove(2, nCharNum - 1);
  test.Insert(2, "..") // this will get you "a..j"

希望这会有所帮助。 (索引可能需要一些修正)

【讨论】:

  • 谢谢,但你建议的不是 textTrimming 它是字符串操作,我需要修剪的文本取决于 ui 元素的宽度,而不是硬编码的决定。
  • 当某些 textox 小于某个值时,是否要替换内部字符?对吗?
  • @Erez:你原来的问题在哪里指定?你不能指望一个不精确的问题得到一个“正确”的答案,如果一个答案确实回答了书面问题,那么它当然不应该被否决。
  • 我觉得这个问题很准确。
猜你喜欢
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 2014-09-23
  • 2011-07-04
  • 2011-08-09
  • 2014-05-05
  • 1970-01-01
相关资源
最近更新 更多