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

本文关键字:网格 数据网 数据 调用 Load 何知道 DataGridCell | 更新日期: 2023-09-27 18:26:47

我想为不同的数据网格调用相同的例程,然后根据数据网格名称进行切换。我试过手机。父母亲但这总是空的。。

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

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

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

使用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;
        }