【问题标题】:LostFocus Binding missing setter callLostFocus 绑定缺少设置器调用
【发布时间】:2017-03-22 12:41:24
【问题描述】:

TextBox 上的双向 Binding 有问题。

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

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

【问题讨论】:

    标签: wpf data-binding setter updatesourcetrigger


    【解决方案1】:

    我自己找到了解决方法。但也许有人有比这更好的解决方案。现在我操纵GotFocus 的值。然后总是在离开控件焦点时调用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 1970-01-01
      • 2011-12-19
      • 2020-06-14
      • 1970-01-01
      相关资源
      最近更新 更多