Lostfocus event in a datagrid

I want lost focus event to be implemented for a column in a datagrid in wpf. I have used CellEditEnding event but this is getting raised on the start of editing not at the end. Please someone help me.

The solution provided by Esam works needs a little edit:

XAML remains the same:

  <DataGrid.CellStyle>
   <Style TargetType="{x:Type DataGridCell}">
      <EventSetter Event="LostFocus" Handler="OnCellLostFocus"/>
   </Style>
</DataGrid.CellStyle>

Code behind to be adapted:

private void OnCellLostFocus(object sender, RoutedEventArgs e)
    {
        var myCell = sender as DataGridCell;
        if (myCell.Column.Header.ToString() == "Name of the column")
        {
            MessageBox.Show("tralala. I got it");
            //do whatever needed here
        }
    }

WPF Datagrid lost focus event fires everytime - MSDN, But my issue is lost focus event fires every time even I click on datagrid cell to update text content. Is there any specific event I can use when  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more Selected Row on WPF Datagrid LostFocus mvvm Pattern

i have used that event and it's working perfect. my xaml Code Look like

<DataGrid AutoGenerateColumns="False" Height="256" HorizontalAlignment="Left" Name="dgEmp" VerticalAlignment="Top" Width="490"  ItemsSource="{Binding DeleteDate,Mode=TwoWay}" Margin="6,7,0,0" CanUserDeleteRows="True" RowEditEnding="dgEmp_RowEditEnding"  CellEditEnding="dgEmp_CellEditEnding" Grid.RowSpan="3">
                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ID" Binding="{Binding ID,Mode=TwoWay}" IsReadOnly="True" Visibility="Hidden"/>
                        <DataGridTextColumn Header="Description" Binding="{Binding Description,Mode=TwoWay}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Amount" Binding="{Binding Amount,Mode=TwoWay}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Date" Binding="{Binding Date,Mode=TwoWay}" IsReadOnly="True"/>
                        <DataGridTextColumn Header="Remark" Binding="{Binding Remark,Mode=TwoWay}" IsReadOnly="True"/>
                        <DataGridTemplateColumn>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Content="Update" x:Name="btnUpdate"
                            Click="btnUpdate_Click"></Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTemplateColumn>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <Button Content="Delete" x:Name="btnDelete"
                            Click="btnDelete_Click"></Button>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                    </DataGrid.Columns>
                </DataGrid>

in my .cs file Code look like

   private void dgEmp_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
        var update = from p in Context.Expense_Submits where p.ID == objEmpToEdit.ID select p;
        foreach (var item in update)
            {
            item.ID = objEmpToEdit.ID;
            item.Description = objEmpToEdit.Description;
            item.Date = objEmpToEdit.Date;
            item.Amount = objEmpToEdit.Amount;
            item.Remark = objEmpToEdit.Remark;
            }
        Context.SubmitChanges();
        MessageBox.Show("The Current row updation is complete..");
        }


  private void dgEmp_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {

        if (isUpdateMode) //The Row is edited
            {
            Expense_Submit exp_sub = (from exp in submit where exp.ID == objEmpToEdit.ID select exp).FirstOrDefault();
            FrameworkElement element_1 = dgEmp.Columns[1].GetCellContent(e.Row);
            if (element_1.GetType() == typeof(TextBox))
                {
                var Description = ((TextBox)element_1).Text;
                objEmpToEdit.Description = Description.ToString();

                }

            FrameworkElement element_2 = dgEmp.Columns[2].GetCellContent(e.Row);
            if (element_2.GetType() == typeof(TextBox))
                {
                var Amount = ((TextBox)element_2).Text;
                objEmpToEdit.Amount = Amount.ToString();
                }

            FrameworkElement element_3 = dgEmp.Columns[3].GetCellContent(e.Row);
            if (element_3.GetType() == typeof(TextBox))
                {
                var Date = ((TextBox)element_3).Text;
                objEmpToEdit.Date = Convert.ToDateTime(Date);
                }

            FrameworkElement element_4 = dgEmp.Columns[4].GetCellContent(e.Row);
            if (element_4.GetType() == typeof(TextBox))
                {
                var Remark = ((TextBox)element_4).Text;
                objEmpToEdit.Remark = Remark.ToString();
                }


            }


        }
 private void dgEmp_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        objEmpToEdit = dgEmp.SelectedItem as Expense_Submit;
        }

DataGridView.CellLeave Event (System.Windows.Forms), Occurs when a cell loses input focus and is no longer the current cell. public: event System::Windows::Forms::DataGridViewCellEventHandler ^ CellLeave;. C# A more precise interpretation of this event is that it is raised when the value of the IsFocused property of an element in the route changes from true to false. Because this event uses bubbling routing, the element that loses focus might be a child element instead of the element where the event handler is actually attached.

Why not use LostFocus event on cells, then check if the cell belongs to the column you want.

For example:

<DataGrid.CellStyle>
   <Style TargetType="{x:Type DataGridCell}">
      <EventSetter Event="LostFocus" Handler="OnCellLostFocus"/>
   </Style>
</DataGrid.CellStyle>

Then in the handler:

private void OnCellLostFocus(object sender, RoutedEventArgs e)
    {
        if (((DataGridCell)sender).Column.Header == "My Column")
            //do stuff
    }

How to Validate WPF Datagrid Cell on Lost Focus to check null , GetContainerFromItem(item) as Xceed.Wpf.DataGrid.DataRow;. row.Cells[​fieldName].Content = 12;. And then to fire lost focus event manually  It also demonstrates handling the LostFocus event by setting the FileDialog.InitialDirectory property to the text in TextBox1. The code example used the ErrorProvider.GetError method to check for an error before opening the file dialog box. To run this example, paste the following code into a form containing a TextBox named TextBox1, an OpenFileDialog named OpenFileDialog1, a Button named Button1, and an ErrorProvider named ErrorProvider1.

Firing datagrid cell lostfocus event by code. – Xceed, In this example the selection background color is set in the CellEnter event, then reset to Empty on the CellLeave event. To run this example, paste the code into a form that contains a DataGridView named dataGridView1 and ensure that all events are associated with their event handlers.

Why not use LostFocus event on cells, then check if the cell belongs to the column you want. For example: <DataGrid.CellStyle> <Style TargetType="{x:Type DataGridCell}"> <EventSetter Event="LostFocus" Handler="OnCellLostFocus"/> </Style> </DataGrid.CellStyle> Then in the handler:

<DataGrid.RowValidationRules> <local:CourseValidationRule ValidationStep="UpdatedValue"/> </DataGrid.RowValidationRules> When a user specifies an end date that is earlier than the start date, a red exclamation mark (!) appears in the row header. You can change this default validation feedback as described in the following procedure.

Comments
  • You gotta add "ToString()" to make this work : if (((DataGridCell)sender).Column.Header.ToString() == "My Column")