LostFocus绑定缺少的setter call

时间:2017-03-22 12:41:24

标签: wpf data-binding setter updatesourcetrigger

我对Binding上的双向TextBox存在问题。

<TextBox Text="{Binding Path=MyText, Mode="TwoWay", UpdateSourceTrigger=LostFocus}" />

离开此元素的焦点后,即使MyText属性未发生变化,我也希望进行Text的二次调用。

public string MyText {
    get { return _myText; }
    set {
        if (value == _myText) {
            RefreshOnValueNotChanged();
            return;
        }
        _myText = value;
        NotifyOfPropertyChange(() => MyText);
    }
}

永远不会调用测试函数RefreshOnValueNotChanged()。有谁知道一招?我需要UpdateSourceTrigger=LostFocus,因为Enter的附加行为(我需要一个完整的用户输入......)。

<TextBox Text="{Binding Path=MyText, Mode="TwoWay", UpdateSourceTrigger=LostFocus}" >
    <i:Interaction.Behaviors>
        <services2:TextBoxEnterBehaviour />
    </i:Interaction.Behaviors>
</TextBox>

上课:

public class TextBoxEnterBehaviour : Behavior<TextBox>
{
    #region Private Methods

    protected override void OnAttached()
    {
        if (AssociatedObject != null) {
            base.OnAttached();
            AssociatedObject.PreviewKeyUp += AssociatedObject_PKeyUp;
        }
    }

    protected override void OnDetaching()
    {
        if (AssociatedObject != null) {
            AssociatedObject.PreviewKeyUp -= AssociatedObject_PKeyUp;
            base.OnDetaching();
        }
    }

    private void AssociatedObject_PKeyUp(object sender, KeyEventArgs e)
    {
        if (!(sender is TextBox) || e.Key != Key.Return) return;
        e.Handled = true;
        ((TextBox) sender).MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }

    #endregion
}

1 个答案:

答案 0 :(得分:0)

我找到了自己的解决方法。但也许有人有比这更好的解决方案。现在我操纵GotFocus处的值。然后在离开Controls Focus ...

时始终调用setter
<TextBox Text="{Binding Path=MyText, Mode="TwoWay", UpdateSourceTrigger=LostFocus}" GotFocus="OnGotFocus" >
    <i:Interaction.Behaviors>
        <services2:TextBoxEnterBehaviour />
    </i:Interaction.Behaviors>
</TextBox>

使用:

private void OnGotFocus(object sender, RoutedEventArgs e)
{
    var tb = sender as TextBox;
    if(tb == null) return;
    var origText = tb.Text;
    tb.Text += " ";
    tb.Text = origText;
}