views:

33

answers:

4

Hi, I have a textbox and have an onlostfocus event on it.

Inside the lostfocus method, is there a way I can determine if the user has actually changed the value in it? i.e how do i get hold of any previous value in it?

Thanks

A: 

Store the original value somewhere. You could write a common component to store the value when it gets focus and compare the value when it loses focus. I've done this in ASP.NET and it works quite well.

Kendrick
That looks good ... thanks ill try that!
guest
A: 
Matthew
Thanks for the replies guys...but is it possible to check for it without storing value in a local variable? Seems a bit unclean
guest
@guest I would say no as once the dependency property TextProperty is written you don't have access to old values. TextBox doesn't contain the state information for change tracking ( see http://msdn.microsoft.com/en-us/library/system.windows.controls.textbox_members.aspx ). You could always create a new UserControl that contains a textbox and neatly contains the additional logic and state for change tracking.
Matthew
+2  A: 

As with just about everything else in WPF, this is easier if you use data binding.

Bind the text box to a class property. By default, bindings update the source when the bound control loses focus, so you don't have to muck around with the LostFocus event. You then have access to both the new value and the value that the user entered in the property setter.

In the XAML it looks like this:

<TextBox Text="{Binding MyProperty, Mode=TwoWay}"/>

In the class it looks like this:

private string _MyProperty;

public string MyProperty
{
   get { return _MyProperty; }
   set
   {
      // at this point, value contains what the user just typed, and 
      // _MyProperty contains the property's previous value.
      if (value != _MyProperty)
      {
         _MyProperty = value;
         // assuming you've implemented INotifyPropertyChanged in the usual way...
         OnPropertyChanged("MyProperty"); 
      }
   }
Robert Rossney
The fellow below answers the question correctly, but you answer the problem correctly, +1 for you.
Jimmy Hoffa
A: 

Another way to solve this by databinding: Bind the TextBox.Text to the property, that holds the inital value, but use a binding with UpdateSourceTrigger=Explicit Then, when the textbox loses focus, you can check the binding if source and target values differ, using this code snippet and evaluating the resulting BindingExpression: BindingExpression be = tb.GetBindingExpression(TextBox.TextProperty); Some more code can be found here: http://bea.stollnitz.com/blog/?p=41

Simpzon