WinRT TextBox MaxLength 不将 \n\r 计为两个字符

WinRT TextBox MaxLength does not count \n\r as two characters

我将 TextBoxMaxLength 设置为 10,但当按下 Enter 键时它接受 11 个字符。看起来它正在将 \n\r 计为 1 个字符而不是两个。有没有办法让它把 \n\r 算作两个字符的长度?

如果您真的想在文本框中允许换行并限制其文本长度,我看到两个选项:

  • 要么通过转换器绑定MaxLength,使其根据文本包含的换行符(\r\n)的数量改变其值,如this question
  • 或者,您可以定义自己的附加 属性 MaxLength 来正确计算文本长度。这可能看起来有点像以下内容(作为示例,您需要对其进行调整以考虑特殊情况等):

    public class TextBoxExtensions: DependencyObject
    {
        public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached(
            "MaxLength", typeof (int), typeof (MaxLengthBehavior), new PropertyMetadata(default(int), PropertyChangedCallback));
    
        public static void SetMaxLength(DependencyObject element, int value)
        {
            element.SetValue(MaxLengthProperty, value);
        }
    
        public static int GetMaxLength(DependencyObject element)
        {
            return (int) element.GetValue(MaxLengthProperty);
        }
    
        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            var tb = dependencyObject as TextBox;
            if (tb != null)
            {
                tb.KeyDown -= TbOnKeyDown;
                tb.KeyDown += TbOnKeyDown;
            }
        }
    
        private static void TbOnKeyDown(object sender, KeyRoutedEventArgs args)
        {
            var tb = sender as TextBox;
            if (tb != null)
            {
                int max = GetMaxLength(tb);
                if (tb.Text.Length >= max)
                    args.Handled = true;
            }
        }
    }
    

<TextBox local:TextBoxExtensions.MaxLength="10" />