WPF验证未绑定文本框

5

不绑定对象,是否可以使用验证功能?我的文本框没有绑定到任何对象,但我仍然想验证其内容。目前我找到的唯一方法是:

    <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个回答

3

根据MSDN论坛的说法,目前还不可能实现,但已经计划了(注意:这是一篇旧帖子)。然而,我仍然找不到方法来做到这一点,所以可能尚未实现。


是的,我想我得自己写代码了。我认为微软专注于绑定的想法很好,但是由于这个目的而限制验证的方式并不太好。谢谢,Lucas。 - Carlo
嗨,这个主题有什么更新吗?我也想做同样的事情。 - Igor Kondrasovas

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类。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接