2014-04-24 51 views
2

我正在嘗試爲Windows Phone 8(Silverlight)創建一個具有特殊行爲的正常TextBox的文本框。
行爲在於ViewModel在用戶鍵入時立即更新,而不是在TextBox失去焦點時更新。
這是我現在已經和正在...以編程方式添加Interaction.Behavior

<TextBox Text="{Binding Path=Email,Mode=TwoWay}" InputScope="EmailNameOrAddress"> 
    <i:Interaction.Behaviors> 
     <helpers:UpdateTextBindingOnPropertyChanged /> 
    </i:Interaction.Behaviors> 
</TextBox> 

我想創建文本框的FastTextbox子類,在默認情況下此行爲。
如何以編程方式添加此行爲?

我嘗試這樣做:

public class FastTextbox:System.Windows.Controls.TextBox 
{ 
    public FastTextbox() 
    { 
     BehaviorCollection Behaviors= Interaction.GetBehaviors(this); 
     Behaviors.Add(new UpdateTextBindingOnPropertyChanged()); 
    } 
} 

但我在行爲得到一個錯誤。
我使用的行爲使用下面的代碼來確定它的表達式(失敗)。

protected override void OnAttached() 
{ 
    base.OnAttached(); 

    // expression gets null here :(
    _expression = AssociatedObject.GetBindingExpression(TextBox.TextProperty); 
    AssociatedObject.TextChanged += OnTextChanged; 
} 

我該怎麼做?

+0

在我看來,還是你在文本框的構造失蹤的InitializeComponent? – csharpwinphonexaml

+0

@verdesrobert :(聲明:我沒有爲WP7/8編程,但假設他們的Silverlight Framework提供了一個類似於桌面版的API)'InitializeComponent'僅用於UserControls。 – Martin

回答

1

問題是:只要你沒有設置任何綁定到你的FastTextbox.Text屬性GetBindingExpression將返回null。這是絕對正確的行爲。目前還沒有約束性表達。

[編輯] 一種解決方案可能是:也許有對OnTextChanged或OnTextPropertyChanged的覆蓋,你可以有調用GetBindingExpression方法。

[編輯] 您能使用Text="{Binding Path=Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"嗎?需要FastTextbox將停止。

+0

謝謝馬丁..你讓我走在正確的軌道上 – Gluip

1

實際的解決方案是非常簡單:)

public FastTextbox() 
    { 
     TextChanged += OnTextBoxTextChanged; 
    } 

    private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e) 
    { 
     TextBox senderText = (TextBox)sender; 
     BindingExpression bindingExp = senderText.GetBindingExpression(TextProperty); 
     bindingExp.UpdateSource(); 
    }