Search code examples
c#wpfdatagridcellparent

DataGridCell_Load how to know the name of the calling datagrid


I want to call the same routine for different datagrids and then to switch according to the datagrid name. I tried cell.Parent. but that is always null..

private void DataGridCell_Load(object sender, RoutedEventArgs e)
{
     DataGridCell cell = sender as DataGridCell;
     if (cell.Column.DisplayIndex == 2 || cell.Column.DisplayIndex == 3 || cell.Column.DisplayIndex == 4)
     {
         try
         {
            double dVal = Math.Round(double.Parse(((TextBlock)cell.Content).Text),3);
            ((TextBlock)cell.Content).Text = dVal.ToString("0.00");
         }
         catch (Exception)
         {
            Console.WriteLine("EXC");
         }
     }
 }

Solution

  • <DataGrid.Resources>
        <Style TargetType="DataGridCell">
            <EventSetter Event="DataGridCell.Loaded" Handler="DataGridCell_Load"/>
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
        </Style>
    </DataGrid.Resources>
    
    
    
    private void DataGridCell_Load(object sender, RoutedEventArgs e)
            {
                DataGridCell cell = sender as DataGridCell;
                DataGrid parentGrid = (DataGrid)(cell.Tag);
            }