TextBox MaxLength 属性 正在计算空格

TextBox MaxLength property is counting whitespace

我的文本框有 MaxLength 设置的 100 个字符的限制 属性。

但是,如果用户键入“\n”或“\t”,它们将被计为一个额外的字符,这对程序员来说有意义,但对用户来说没有意义。

除了自己统计字数还有什么办法吗?

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

<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,依此类推。

我真的很喜欢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>