【问题标题】:WPF Validating unbound textboxWPF验证未绑定的文本框
【发布时间】:2010-12-02 01:26:48
【问题描述】:

是否可以在没有绑定部分的情况下使用验证?问题是我的文本框没有绑定到任何对象,但我仍然想验证它的内容。到目前为止我发现的唯一方法是:

    <TextBox Grid.Row="0" Grid.Column="1" MaxLength="50" x:Name="textBoxTubeName" Margin="5,5,0,5">
        <TextBox.Text>
            <Binding Path="Name" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                    <validation:InvalidCharactersRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

但同样,它仅在 TextBox.Text 绑定到某个东西(在本例中为 Name 属性)时才有效,如果没有绑定,我该如何处理?

谢谢!

【问题讨论】:

    标签: wpf validation binding textbox


    【解决方案1】:

    According to the MSDN forums 目前还不可能,但已在计划中(注意:这是一篇旧帖子)。但是,我仍然找不到方法,所以它可能还没有实现。

    【讨论】:

    • 是的,我想我必须自己编写代码。我认为微软专注于绑定的想法是好的,但是由于这个目的而限制验证的方式并不是那么好。谢谢卢卡斯。
    • 嗨。关于这个主题有任何更新吗?我也想这样做。
    【解决方案2】:

    从代码隐藏中执行非常棘手。基本上,您可以从代码中设置临时绑定并引发验证错误,当输入具有有效值时,您可以再次删除所有临时绑定内容。

    这是我使用的,我认为这是一种不好的做法(但从无到有更好):

        /// <summary>
        /// Marks a textBox control as invalid (via validation error) from code.
        /// </summary>
        /// <param name="textBox">The text box.</param>
        /// <param name="errorContent">Content of the error.</param>
        public static void ValidationMarkInvalid(TextBox textBox, String errorContent)
        {
            DependencyProperty textProp = TextBox.TextProperty;
            if (!BindingOperations.IsDataBound(textBox, textProp))
            {
                if (textBox.DataContext == null)
                {
                    textBox.DataContext = new EmptyDataContext();
                }
    
                Binding b = new Binding("CodeBehind");
                b.FallbackValue = textBox.Text;
                b.ValidatesOnExceptions = true;
                BindingOperations.SetBinding(textBox, textProp, b);
            }
    
            BindingExpression bindingInError =
                textBox.GetBindingExpression(TextBox.TextProperty);
    
            var validationError = new ValidationError(
                new EmptyValidationRule(),
                bindingInError,
                errorContent,
                new Exception(errorContent));
    
            Validation.MarkInvalid(bindingInError, validationError);
        }
    
        /// <summary>
        /// Clears the validation error from a textBox.
        /// </summary>
        /// <param name="textBox">The text box.</param>
        public static void ValidationClear(TextBox textBox)
        {
            DependencyProperty textProp = TextBox.TextProperty;
            if (BindingOperations.IsDataBound(textBox, textProp))
            {
                String value = textBox.Text;
                Validation.ClearInvalid(textBox.GetBindingExpression(TextBox.TextProperty));
                BindingOperations.ClearBinding(textBox, textProp);
                textBox.Text = value;
    
                EmptyDataContext ctx = textBox.DataContext as EmptyDataContext;
                if (ctx != null)
                {
                    textBox.DataContext = null;
                }
            }
        }
    
        #region Nested Type: EmptyDataContext
        private sealed class EmptyDataContext : INotifyPropertyChanged
        {
            public Object CodeBehind
            {
                get
                {
                    throw new FormatException();
                }
                set
                {
                    throw new FormatException();
                }
            }
    
            #region INotifyPropertyChanged Members
            public event PropertyChangedEventHandler PropertyChanged;
            #endregion
        }
        #endregion
    
        #region Nested Type: EmptyValidationRule
        private sealed class EmptyValidationRule : ValidationRule
        {
            /// <summary>
            /// When overridden in a derived class, performs validation checks on a value.
            /// </summary>
            /// <param name="value">The value from the binding target to check.</param>
            /// <param name="cultureInfo">The culture to use in this rule.</param>
            /// <returns>
            /// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
            /// </returns>
            public override ValidationResult Validate(Object value, CultureInfo cultureInfo)
            {
                return new ValidationResult(false, String.Empty);
            }
        }
        #endregion
    

    现在,从您的代码隐藏中执行以下操作:

    ValidationMarkInvalid(textBox, "Please enter something valid!");
    

    并清除验证:

    ValidationClear(textBox);
    

    P.S.:如果您不想验证异常,可以从上述方法中删除 EmptyDataContext 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 1970-01-01
      • 2015-04-21
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多