DataGridCell_Load 如何知道调用数据网格的名称

DataGridCell_Load how to know the name of the calling datagrid

我想为不同的数据网格调用相同的例程,然后根据数据网格名称进行切换。我试过了cell.Parent。但这总是空的..

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");
         }
     }
 }

使用 VisualTreeHelper 您可以从 DataGridCell 中找到父项。

        DependencyObject dep = (DependencyObject)e.OriginalSource; 
        var cell = dep as System.Windows.Controls.DataGridCell;
        while ((dep != null) && !(dep is DataGridRow))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        var row = dep as DataGridRow;
        if (row != null)
        {
            var dataGrid = ItemsControl.ItemsControlFromItemContainer(row) as System.Windows.Controls.DataGrid;
            return dataGrid;
        }
<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);
        }