WPF验证未绑定的文本框

时间:2009-09-28 16:26:50

标签: wpf validation binding textbox

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

    <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属性)时才会起作用,如何在没有绑定的情况下进行此操作?

谢谢!

2 个答案:

答案 0 :(得分:3)

According to the MSDN forums这还不可能,但计划好了(注意:这是一篇旧帖子)。但是,我仍然找不到办法,因此可能尚未实施。

答案 1 :(得分: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类。