how to add CharacterEllipsis at the beginning of the textblock in wpf?
Asked Answered
B

2

6

I have a TextBlock with TextTrimming = TextTrimming.CharacterEllipsis and I want the dots to appear at the beginging. Is there a property for this?

For example if I have the text "123456789ABCDEF" it is displayed "12345678...", but I want it "...89ABCDEF".

Thanks

Blazonry answered 29/11, 2010 at 9:34 Comment(0)
P
2

I had a go at messing about with FlowDirection, it renders the ... at the beginning but still started with 1234 etc.

I did however come across this very similar question:

Ellipsis at start of string in WPF ListView

Someone there has a routine to do it manually. Hope that helps :)

Pledge answered 29/11, 2010 at 9:49 Comment(1)
I've made a more usable approach on that question, just check it outParfleche
N
0

Just for people still in search of a "quick and simple" answer. Using a converter can be a good way to go :

public class TextTrimmingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value is string stringValue)
    {
        var paramInt = parameter?.ToInt(int.MaxValue); // this ToInt is custom, use whatever to convert your param (the max size of you textblock) into int
        if (paramInt == int.MaxValue)
            return stringValue;

        var formattedText = new FormattedText(stringValue,
                                              CultureInfo.GetCultureInfo("en-us"),
                                              FlowDirection.LeftToRight,
                                              new Typeface("Arial"),
                                              14,
                                              Brushes.Black);
        var textWidth = formattedText.Width;
        if (textWidth > paramInt)
            return $"...{stringValue.Substring(stringValue.Length / 2)}"; // use a substring length that fits you
        return stringValue;
    }
    return value;
}

public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing;

Then use it that way :

                        <TextBlock Text="{Binding MyTextToTrim,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,Converter={StaticResource TextTrimmingConverter},ConverterParameter=150}"
                               MaxWidth="150"
                               VerticalAlignment="Center" />
Nympho answered 24/9 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.