2013-05-15 36 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()之后。我确定了我的答案,但其中的一部分仍然相关。 –