Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"UpdateSourceTrigger=PropertyChanged" equivalent for a Windows Phone 7 TextBox

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}"/> 
like image 727
Jason Quinn Avatar asked Jan 28 '11 21:01

Jason Quinn


2 Answers

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 the UpdateSource method. It saves you one extra binding set when the user leaves the TextBox.

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(); } 
like image 165
Praetorian Avatar answered Oct 13 '22 01:10

Praetorian


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();   } } } 
like image 28
Parrhesia Joe Avatar answered Oct 13 '22 01:10

Parrhesia Joe