TextBox MaxLength属性正在计算空白

时间:2015-03-08 15:03:29

标签: wpf textbox whitespace maxlength

My TextBox的MaxLength属性设置了100个字符的限制。

但是,如果用户键入' \ n'或者' \ t',它们被视为一个额外的字符,这对程序员有意义,但对用户没有意义。

除了自己计算角色外还有其他解决方法吗?

2 个答案:

答案 0 :(得分:2)

您可以创建自己的附加属性:

<TextBox wpfApplication4:TextBoxBehaviors.MaxLengthIgnoringWhitespace="10" />

附加属性定义如下:

    public static class TextBoxBehaviors
{
    public static readonly DependencyProperty MaxLengthIgnoringWhitespaceProperty = DependencyProperty.RegisterAttached(
        "MaxLengthIgnoringWhitespace",
        typeof(int),
        typeof(TextBoxBehaviors),
        new PropertyMetadata(default(int), MaxLengthIgnoringWhitespaceChanged));

    private static void MaxLengthIgnoringWhitespaceChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
    {
        var textBox = dependencyObject as TextBox;

        if (textBox != null && eventArgs.NewValue is int)
        {
            textBox.TextChanged += (sender, args) =>
                {
                    var maxLength = ((int)eventArgs.NewValue) + textBox.Text.Count(char.IsWhiteSpace);
                    textBox.MaxLength = maxLength;  
                };
        }
    }

    public static void SetMaxLengthIgnoringWhitespace(DependencyObject element, int value)
    {
        element.SetValue(MaxLengthIgnoringWhitespaceProperty, value);
    }

    public static int GetMaxLengthIgnoringWhitespace(DependencyObject element)
    {
        return (int)element.GetValue(MaxLengthIgnoringWhitespaceProperty);
    }
}

代码将使用TextBox现有的MaxLength属性,并且只会增加您输入的空白​​数量。因此,如果将属性设置为10并键入5个空格,则TextBox上的实际MaxLength将设置为15,依此类推。

答案 1 :(得分:1)

我真的很喜欢Toby Crawford回答但是因为我开始尝试一个简单的答案我想加我的:

 public partial class MainWindow : Window
    {
        public string TextLength { get; set; }
        public MainWindow()
        {
            InitializeComponent();
        }

        private void txtInput_TextChanged(object sender, TextChangedEventArgs e)
        {
            var textbox = sender as TextBox;
            var tempText = textbox.Text.Replace(" ", "");
            lblLength.Content = (tempText.Length).ToString();
        }
    }
       <Grid>
            <TextBox HorizontalAlignment="Left" Name="txtInput" MaxLength="{Binding TextMaxLength}" Height="23" Margin="220,67,0,0" TextWrapping="Wrap" Text="" TextChanged="txtInput_TextChanged" VerticalAlignment="Top" Width="120"/>
            <Label Name="lblLength"  HorizontalAlignment="Left" VerticalAlignment="Top" Margin="220,126,0,0"/>
            <Label Content="Your text length" HorizontalAlignment="Left" Margin="93,126,0,0" VerticalAlignment="Top"/>
            <Label Content="Your text" HorizontalAlignment="Left" Margin="93,67,0,0" VerticalAlignment="Top"/>

        </Grid>

enter image description here