DataGridCell_Load如何知道调用datagrid的名称

时间:2015-12-14 15:20:39

标签: c# wpf datagrid cell parent

我想为不同的数据网格调用相同的例程,然后根据数据网格名称进行切换。我试过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");
         }
     }
 }

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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