Jake Wharton
Jake Wharton

Reputation: 76075

TextChanged/LostFocus/etc. event for DataGridTextColumn

I have a list of object bound to a DataGrid in a WPF page and I am looking to add an object directly after the current one if the value entered in a specific column is less than a certain number.

<my:DataGridTextColumn Binding="{Binding Path=Hours}"/>

I cannot for the life of me figure out how to bind to an event on the underlying TextBox. Various sites reference the ability to do this but none provide the associated code. For now I have been using a DataGridTemplateColumn with a TextBox inside of it but I don't seem to the able to get the current row with that solution.

Upvotes: 3

Views: 10646

Answers (2)

Ali Rasouli
Ali Rasouli

Reputation: 1903

You can used this code for all cell and row updated:

<sdk:DataGrid ItemsSource="{Binding Collection}" CellEditEnded="DataGrid_CellEditEnded" RowEditEnded="DataGrid_RowEditEnded">
    <sdk:DataGrid.Columns>
        <sdk:DataGridTextColumn Binding="{Binding Path=Hours}" Width="Auto" />
    </sdk:DataGrid.Columns>
</sdk:DataGrid>

Upvotes: 1

Jake Wharton
Jake Wharton

Reputation: 76075

To accomplish this I used the CellEditEnding event on the data grid itself.

this.TheGrid.CellEditEnding += new EventHandler<DataGridCellEditEndingEventArgs>(TheGrid_CellEditEnding);

In the method you can then use a Dispatcher to delay the call to a method so the value is stored back in the bound object.

private void TheGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    Dispatcher.BeginInvoke(new Action(this.CellEdited));
}

You can also pass the DataGridCellEditEndingEventArgs to the method to allow you to inspect the row and column of the cell that was edited along with the underlying TextBox.

Also since the data grid is concerned about objects the row index is not too relevant and therefore not easily obtainable (that I could find).

Upvotes: 4

Related Questions