2011-11-04 77 views
1

我有从TextBox派生的MyTextBox。我想在MyTextBox中设置Binding Option ValidatesOnDataErrors = True的TextProperty,这样每当我使用这个控件时,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. 

我缺少的东西?

回答

3

我觉得你需要的是特殊的绑定而不是特殊的文本框。

看一看这里:Set ValidatesOnDataErrors for all bindings programmatically

在WPF一旦被使用,你不能改变的结合。

要使您的代码工作,您必须先清除绑定,然后添加一个新的ValidateOnDataErrors设置为true,但听起来像一个混乱的方式...

相关问题