2011-11-04 81 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,但聽起來像一個混亂的方式...

相關問題