2012-09-17 28 views
0

幾天前,我意識到在Silverlight中,爲了始終更新任何texbox上的綁定(爲了驗證每個KeyPress中的錯誤),我需要此代碼對TextChanged事件事件文本框我的系統出現:在View上分配事件時,無法引用基類方法

TextBox txCtl = (TextBox)sender; if (txCtl != null) 
{ 
    var be = txCtl.GetBindingExpression(TextBox.TextProperty); 

    if (be != null) 
    { 
     be.UpdateSource(); 
    } 
} 

此代碼工作得很好(來源:http://forums.silverlight.net/t/51100.aspx/1)。問題是:我不想在CodeBehind的每個視圖中重複它,所以我決定創建一個自定義的ViewBase,我將這個代碼留在它上面。我所做的只是:

public class ViewBase : ChildWindow 
{ 
    protected void tboxTextChanged(object sender, TextChangedEventArgs e) 
    { 
     TextBox txCtl = (TextBox)sender; if (txCtl != null) 
     { 
      var be = txCtl.GetBindingExpression(TextBox.TextProperty); 

      if (be != null) 
      { 
       be.UpdateSource(); 
      } 
     } 
    } 
} 

然後我認爲現在是一個ViewBase而不是用戶控件,所以我也改變了XAML到:

<src:ViewBase x:Class="Oi.SCPOBU.Silverlight.Pages.CadastroClassificacao" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:src="clr-namespace:Oi.SCPOBU.Silverlight.Pages" [...] 

最後,在我的文本框我離開事件引用相同的方法像往常一樣,但現在的方法是在ViewBase,在代碼隱藏是istead:

<TextBox 
    x:Name="tbxNome" 
    Width="300" 
    MaxLength="50" 
    HorizontalAlignment="Left" 
    TextChanged="tboxTextChanged" 
    Text="{Binding DTOClassificacao.Nome, Mode=TwoWay, NotifyOnValidationError=True> 

看起來很簡單的給我,但這行不通。代碼編譯,但在運行時,我得到錯誤:「消息=未能分配給屬性'System.Windows.Controls.TextBox.TextChanged'。[Line:43 Position:37]」,在InitializeComponent()方法上。

任何人都知道如何從我的基類中分配一個方法到一個事件?或者我真的不得不在我看到的每個視圖中重複這些代碼?

+0

是否有任何內部異常? – nemesv

+0

不,就是這樣。 – Piscies

回答

1

in order to always update the bindings on any texbox (in order to validate for error in each KeyPress) I needed this code on TextChanged Event event in every TextBox I had in the system

你試過UpdateSourceTrigger.PropertyChanged

<TextBox Text="{Binding Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> 
+0

你是我的英雄。我試圖找到一種方法來更新源代碼的綁定幾個小時,並在Silverlight論壇上的帖子就是我所擁有的。非常感謝你=)[我不能upvote你的答案,因爲我在這裏是新的,所以我還沒有任何聲譽=(] – Piscies