2017-03-22 67 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; 
}