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

时间:2015-09-03 14:06:29

标签: windows-runtime windows-store-apps

@app.route('/admin/dashboard', methods=['GET', 'POST']) def admin_dashboard(): if request.method == 'GET': return render_template("/admin/dashboard.html") if request.method == 'POST': if request.form['submit'] == 'fred': admin.log("Shutting down...") #os._exit(1) else: return render_template("/admin/dashboard.html") return render_template("/admin/dashboard.html") TextBox设为10,但按Enter键时接受11个字符。看起来它将 \ n \ r 计为1个字符而不是2个字符。反正有没有把它计算为 \ n \ r 两个字符长度?

1 个答案:

答案 0 :(得分:2)

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

  • 通过转换器绑定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" />