2017-03-22 70 views
0

我在TextBox上遇到双向Binding问题。LostFocus Binding missing setter call

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

回答

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