简体   繁体   English

用绑定更新文本框时限制其字符串长度

[英]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. 我知道您可以通过设置MaxLength属性来限制用户的TextBox输入字符。

Is there a similar way to limit the number of characters shown in Text when the Text is updated with Binding ? 有没有类似的方式限制所示的字符数Text时, Text与更新Binding For example, when it is updated from Binding just show the first 5 characters and leave the rest? 例如,从Binding更新时,仅显示前5个字符,剩下的保留?

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);
        }
    }

This should work: 这应该工作:

Xaml: 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();
        }
    }

I hope to understand you right. 我希望正确理解你。 You could create a new Property in the ViewModel that returns only the first 5 chars of the text and set your binding to that property. 您可以在ViewModel中创建一个新属性,该属性仅返回文本的前5个字符,并将绑定设置为该属性。 You might need to call PropertyChanged for the new Property when the text changes. 文本更改时,您可能需要为新的Property调用PropertyChanged。

A simple but very flexible way of doing it would be to introduce a projected property in your Viewmodel that returns the first 5 characters of the original property and then bind your control to this property. 一种简单但非常灵活的方法是在Viewmodel中引入一个投影属性,该属性返回原始属性的前5个字符,然后将控件绑定到该属性。 Since you're only showing part of the property value, I assume that you don't want to write to this property from that TextBox. 由于您仅显示部分属性值,因此我假设您不想从该TextBox写入此属性。 So make you projected property read-only too. 因此,也使您将属性投影为只读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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