0

BindingTextBox.

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

在离开这个元素的焦点时,我希望有一个 setter 调用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
}
4

1 回答 1

0

我找到了自己的解决方法。但也许有人有比这更好的解决方案。现在我操纵GotFocus. 然后总是在离开控制焦点时调用设置器......

<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;
}
于 2017-03-22T13:01:36.900 回答