TextChanged event fires two times rather than once

Oct 14, 2008 at 5:10 AM
Hi,

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

Code snippet....

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

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?

Thanks.
Coordinator
Oct 14, 2008 at 2: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 1: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?

Coordinator
Oct 31, 2008 at 3: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.