Is there a way to get a TextBox in Windows Phone 7 to update the Binding as the user types each letter rather than after losing focus?
Like the following WPF TextBox would do:
<TextBox Text="{Binding Path=TextProperty, UpdateSourceTrigger=PropertyChanged}"/>
Silverlight for WP7 does not support the syntax you've listed. Do the following instead:
<TextBox TextChanged="OnTextBoxTextChanged" Text="{Binding MyText, Mode=TwoWay, UpdateSourceTrigger=Explicit}" />
UpdateSourceTrigger = Explicit
is a smart bonus here. What is it? Explicit: Updates the binding source only when you call theUpdateSource
method. It saves you one extra binding set when the user leaves theTextBox
.
In C#:
private void OnTextBoxTextChanged( object sender, TextChangedEventArgs e ) { TextBox textBox = sender as TextBox; // Update the binding source BindingExpression bindingExpr = textBox.GetBindingExpression( TextBox.TextProperty ); bindingExpr.UpdateSource(); }
I like using an attached property. Just in case you're into those little buggers.
<toolkit:DataField Label="Name"> <TextBox Text="{Binding Product.Name, Mode=TwoWay}" c:BindingUtility.UpdateSourceOnChange="True"/> </toolkit:DataField>
And then the backing code.
public class BindingUtility { public static bool GetUpdateSourceOnChange(DependencyObject d) { return (bool)d.GetValue(UpdateSourceOnChangeProperty); } public static void SetUpdateSourceOnChange(DependencyObject d, bool value) { d.SetValue(UpdateSourceOnChangeProperty, value); } // Using a DependencyProperty as the backing store for … public static readonly DependencyProperty UpdateSourceOnChangeProperty = DependencyProperty.RegisterAttached( "UpdateSourceOnChange", typeof(bool), typeof(BindingUtility), new PropertyMetadata(false, OnPropertyChanged)); private static void OnPropertyChanged (DependencyObject d, DependencyPropertyChangedEventArgs e) { var textBox = d as TextBox; if (textBox == null) return; if ((bool)e.NewValue) { textBox.TextChanged += OnTextChanged; } else { textBox.TextChanged -= OnTextChanged; } } static void OnTextChanged(object s, TextChangedEventArgs e) { var textBox = s as TextBox; if (textBox == null) return; var bindingExpression = textBox.GetBindingExpression(TextBox.TextProperty); if (bindingExpression != null) { bindingExpression.UpdateSource(); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With