以编程方式添加Interaction.Behavior

时间:2014-04-24 19:51:24

标签: c# silverlight windows-phone-7 windows-phone-8

我正在尝试为Windows Phone 8(Silverlight)创建一个文本框,其行为类似于具有特殊行为的普通TextBox。
行为是用户键入后立即更新ViewModel,而不是TextBox失去焦点时 这是我现在所做的工作......

<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;
}

我该怎么做?

2 个答案:

答案 0 :(得分:1)

问题是:只要您未对FastTextbox.Text属性设置任何绑定,GetBindingExpression将返回null。这绝对是正确的行为。还没有绑定表达。

[编辑] 一种解决方案可能是:可能有OnTextChanged或OnTextPropertyChanged的覆盖,您可以在那里调用GetBindingExpression方法。

[EDIT2] 你能用Text="{Binding Path=Email, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"吗? FastTextbox的需求将停止。

答案 1 :(得分:1)

实际解决方案非常简单:)

    public FastTextbox()
    {
        TextChanged += OnTextBoxTextChanged;
    }

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