Coding Geek

A blog by Nadeem Iqbal

SilverLight Text Formatting

There are scenarios when you want to Format the bound string value for example you want to display the long names as nadeemIq... or display a different value based on the bound string value & get back the original value.

So here is IValueConverter interface which is used to achieve such scenarios in SilverLight. 

 

 public class TextFormatConverter : IValueConverter
    {
        string orgValue = "";
        int maxLength = 15;

        #region IValueConverter Members
        public int MaxLength {
            get
            {
                return maxLength;
            }

            set
            {
                maxLength = value;
            }
        }

        object IValueConverter.Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            String val = value as string;
            orgValue = val;

            string newStr = "";

            if (val.Length > MaxLength)
            {
                newStr = val.Substring(0, MaxLength);

                newStr = newStr + "...";

                return newStr;

            }
            else
            {
                return orgValue;
            }
            
           
        }

        object IValueConverter.ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return orgValue;
        }

        #endregion
    }

 

Above is the complete code of TextFormat class which you can use and customize it.

Moreover you can use it as follows;

<UserControl.Resources>
        <myProject:TextFormatConverter x:Key="TextConverter"></myConverter:TextFormatConverter>
 </UserControl.Resources>

 above code specify the User resource in XAML file.

<TextBlock FontFamily="Lucida Sans " Text="{Binding Name, Converter={StaticResource TextConverter}}" />

 And above line specify the TextBlock whom to apply formating.

Comments

NadeemIqbal's Blog said:

There are scenarios when you want to Format the bound string value for example you want to display the

# October 27, 2008 2:47 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)