TextChanged event fires two times rather than once

Oct 14, 2008 at 4:10 AM

I am using TemplateColumn of dataGrid and I am putting Textblock in CellTemplate and Textbox in CellEditingTemplate.

Code snippet....

<dg:DataGridTemplateColumn Width="80">
                     <TextBlock Text="{Binding Path=Name}"/>
                       <TextBox  Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" TextChanged="OnNameChanged"/>

private void OnNameChanged(object sender, TextChangedEventArgs e)
            TextBox textBox = sender as TextBox;
            // Code for validating entered string.

Its fires the "OnNameChanged" event one time more than it should. e.g. if I typed "h", it fires the event first time with text="h" but again it fires with text="".

And because of this, it fails my validation.

Why its firing twice?

Oct 14, 2008 at 1:39 PM
The text = "" occurs when you commit the cell.  This is an affect of switching out the TextBox with the TextBlock.  For validation purposes, I suggest using a ValidationRule on the binding instead.  It will be called everytime the text changes but will not validate the text = "" when the cell is committed.
Oct 15, 2008 at 12:56 AM
Do you have any example of validationRule?... I was trying to do something like http://www.codeplex.com/wpf/Thread/View.aspx?ThreadId=34776 , but it doesn't work for me (see the my last post). May be I am doing something wrong!! Do u have any idea?

Oct 31, 2008 at 2:15 PM
The sample on this blog post, http://blogs.msdn.com/vinsibal/archive/2008/10/22/wpf-datagrid-and-the-wpftoolkit-have-released.aspx, has an example of using row validation.