Search code examples
c#wpftextbox

Limit the string length of TextBox when it is updated with Binding


I know that you can limit the input characters of TextBox from user by setting MaxLength property.

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding? For example, when it is updated from Binding just show the first 5 characters and leave the rest?

Update: Thanks for all the info, I got inspired by your recommendation and in the end did it with a converter. Here is how I did it, if someone wants to use it later.

    public class StringLimiter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string val = value.ToString();
            if (val.Length < 5)
                return val;
            else
                return val.Substring(0, 5);
        }
    }

Solution

  • This should work:

    Xaml:

    <TextBox Text="{Binding TextToDisplay}" />
    

    Code:

        private const int maxLength = 5;
        private string _textToDisplay = "Hello SO";
        public string TextToDisplay
        {
            get
            {
                if(_textToDisplay.Length > maxLength)
                {
                    return _textToDisplay.Substring(0, maxLength);
                }
                return _textToDisplay;
            }
            set
            {
                _textToDisplay = value;
                RaiseProperyChanged();
            }
        }