1

我有从 TextBox 派生的 MyTextBox。我想在 MyTextBox 中设置 TextProperty 的 Binding Option ValidatesOnDataErrors = True,这样每当我使用这个控件时,ValidatesOnDataErrors 就会被初始化为 True。

这是我的代码:

public class MyTextBox:MyBaseTextBox
{
    public MyTextBox()
    {
        MaxLength = 45;
    }

    protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if (e.Property == TextProperty)
        {
            Binding b = BindingOperations.GetBinding(this, TextProperty);
            if (b != null)
            {
                b.ValidatesOnDataErrors = true;
            }                
        }
    }
}

我总是得到例外:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll

Additional information: Binding cannot be changed after it has been used.

我错过了什么吗?

4

1 回答 1

3

我认为您需要的是特殊绑定而不是特殊文本框。

看看这里:以编程方式为所有绑定设置 ValidatesOnDataErrors

在 WPF 中,绑定一旦使用就无法更改。

要使您的代码正常工作,您必须先清除绑定,然后添加一个新的绑定,并将 ValidatesOnDataErrors 设置为 true,但这听起来很混乱……

于 2011-11-04T09:59:30.673 回答