2013-05-15 32 views
-1

我在CRUD表單中遇到了一些困難。我們有一個保存表單的按鈕,並將IsDefault標誌設置爲true,這樣用戶可以在任意點按回車來保存表單。刷新所有綁定的目標

問題是,當用戶在文本框中鍵入並點擊輸入鍵時,文本框綁定的源不會更新。我知道這是因爲文本框的默認UpdateSourceTrigger功能是LostFocus,我曾用它來解決這個問題,但在其他情況下,這實際上會導致更多問題。

對於標準string領域,這是好的,但是對於像double S和int S上的驗證物業發生變化,所以打字說1.5到綁定到雙源的文本框停止用戶(他們可以鍵入1,但驗證停止小數,他們可以鍵入15然後將光標移回並按.雖然)。

有沒有更好的方法來解決這個問題?我研究了在代碼中刷新窗口中所有綁定的方法,這些代碼是用string.empty發起PropertyChanged事件,但是這隻會刷新目標,而不是源。

回答

2

我的標準解決方案時,我不想設定UpdateSourceTrigger=PropertyChanged的綁定是使用自定義的AttachedProperty,當設置爲true,將當輸入被按下時,將更新綁定的來源。

這裏的附加屬性

// When set to True, Enter Key will update Source 
#region EnterUpdatesTextSource DependencyProperty 

// Property to determine if the Enter key should update the source. Default is False 
public static readonly DependencyProperty EnterUpdatesTextSourceProperty = 
    DependencyProperty.RegisterAttached("EnterUpdatesTextSource", typeof (bool), 
             typeof (TextBoxHelper), 
             new PropertyMetadata(false, EnterUpdatesTextSourcePropertyChanged)); 

// Get 
public static bool GetEnterUpdatesTextSource(DependencyObject obj) 
{ 
    return (bool) obj.GetValue(EnterUpdatesTextSourceProperty); 
} 

// Set 
public static void SetEnterUpdatesTextSource(DependencyObject obj, bool value) 
{ 
    obj.SetValue(EnterUpdatesTextSourceProperty, value); 
} 

// Changed Event - Attach PreviewKeyDown handler 
private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj, 
                  DependencyPropertyChangedEventArgs e) 
{ 
    var sender = obj as UIElement; 
    if (obj != null) 
    { 
     if ((bool) e.NewValue) 
     { 
      sender.PreviewKeyDown += OnPreviewKeyDownUpdateSourceIfEnter; 
     } 
     else 
     { 
      sender.PreviewKeyDown -= OnPreviewKeyDownUpdateSourceIfEnter; 
     } 
    } 
} 

// If key being pressed is the Enter key, and EnterUpdatesTextSource is set to true, then update source for Text property 
private static void OnPreviewKeyDownUpdateSourceIfEnter(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Enter) 
    { 
     if (GetEnterUpdatesTextSource((DependencyObject) sender)) 
     { 
      var obj = sender as UIElement; 
      BindingExpression textBinding = BindingOperations.GetBindingExpression(
       obj, TextBox.TextProperty); 

      if (textBinding != null) 
       textBinding.UpdateSource(); 
     } 
    } 
} 

#endregion //EnterUpdatesTextSource DependencyProperty 

我的副本,它的使用是這樣的:

<TextBox Text="{Binding SomeText}" local:EnterUpdatesTextSource="True" /> 
+0

太棒了。完全+1 –

0

您可以通過使用下面的代碼的更新綁定源:

textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource(); 
+0

奇怪,在我的測試LostFocus事件不是射擊等源沒有被在保存按鈕的事件觸發之前更新。我會重新測試。 –

+0

我重新檢查。你是對的,LostFocus沒有打電話。源更新發生在我調用Close()之後。我確定了我的答案,但其中的一部分仍然相關。 –