简体   繁体   中英

Interrupt text from a textblock with “…” when string is too long

I am using a Long list selector with many elements in an windows phone 8 application. Each item has a textblock and the text of each one can very from few letters to many words. I want to keep the text to one line so I set the TextWrapping property to "NoWrap". I want to add "..." and crop the text if is it too long to fit on the screen. I tried so far to use loading event of each TextBlock and reduce the text until it would fit on the screen. However, when the list has many elements, the loading event doesn't activate for all textblocks. Is there a proper way to solve this?

    private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
    {
        TextBlock txt = sender as TextBlock;
        if (txt == null)
            return;

        if (txt.ActualWidth > 300)
        {
            while (txt.Text.Length > 4 && txt.ActualWidth > 290)
                txt.Text = txt.Text.Substring(0, txt.Text.Length - 4);
            txt.Text = txt.Text.Substring(0, txt.Text.Length - 3);

            txt.Text = txt.Text.Trim(new Char[] { ' ', ',' }) + "...";

        }
    }

Here is a Converter example of how to achieve this:

using System;
using System.Globalization;
using System.Windows.Data;

namespace PhoneApp2
{
    public class TextLengthConverter: IValueConverter
    {
        #region Implementation of IValueConverter

        /// <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 is string)
            {
                int desiredLength;
                if (int.TryParse(parameter.ToString(), out desiredLength))
                {
                    if (desiredLength > 0)
                    {
                        string textIn = value as string;
                        if (textIn.Length > desiredLength // Make sure the truncation is actually needed.
                            && textIn.Length > 3) // Make sure the length if the textIn is longer than the dots so 'something' is shown before the dots.
                        {
                            return textIn.Substring(0, desiredLength - 3) + "...";
                        }
                    }
                }
            }
            return value;
        }

        /// <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 NotImplementedException();
        }

        #endregion
    }
}

To use it in a page, add a resource entry like so:

<phone:PhoneApplicationPage.Resources>
    <PhoneApp2:TextLengthConverter x:Key="TextLengthConverter"/>
</phone:PhoneApplicationPage.Resources>

and attach it to your bound text:

<TextBlock Text="{Binding BoundText, Converter={StaticResource TextLengthConverter}, ConverterParameter=4}"/>

A nice, reusable solution you can add to your collection of converters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM