Search code examples
c#wpfwpf-controlswpfdatagrid

How to call a Control's event handler? Get EventArgs value C#


I am trying to call a OnCellEditEnding event from another event,

private void BillsTableRecords_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    // do stuff here
}

My issue is I don't know how to pass the DataGridCellEditEndingEventArgs into the method, i.e. the e in the below method obviously gives an error as it is referencing RoutedEventArgs not DataGridCellEditEndingEventArgs.

private void BillsRecordsCheckBox_OnChecked(object sender, RoutedEventArgs e)
{   
    BillsTableRecords_OnCellEditEnding(sender, e);
}

So how do obtain the value from DataGridCellEditEndingEventArgs so that I can pass the value in the method? Please note that the DataGrid cell with be selected at this point so it will contain a value.


Solution

  • I wouldn't recommend this approach. Event handlers are to be called by events; their signature does not really fit for a standalone call. In case you execute business code in your event handler, it is also not good design, because your event handlers are UI code, which should be separated from business code.

    The best way to go here is to create a dedicated method that does what you want and call it from both event handlers:

    private void DoStuff(/* add the parameters you need*/) {
        //do stuff
    }
    
    private void BillsTableRecords_OnCellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
    {
        DoStuff();
    }
    
    private void BillsRecordsCheckBox_OnChecked(object sender, RoutedEventArgs e)
    {   
        DoStuff();
    }