2014-04-24 52 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(); 
    }