如何获取 DataGridTextColumn 发件人的数据网格父级

How to get the DataGridTextColumn sender's datagrid parent

您好,我有一个数据网格和下面代码中显示的 DataGridTextColumn:

<DataGridTextColumn Header="" Width="1*" Binding="{Binding FORECAST_MIN, UpdateSourceTrigger=PropertyChanged,NotifyOnTargetUpdated=True}" >
 <DataGridTextColumn.EditingElementStyle>
    <Style TargetType="{x:Type TextBox}">
        <EventSetter Event="LostFocus" Handler="fMin_LostFocus" />                  
    </Style>
</DataGridTextColumn.EditingElementStyle>

现在在 LostFocus 事件中,我想从发件人处获取父数据网格。代码

private void fMin_LostFocus(object sender, RoutedEventArgs e)
{            
//Get the datagrid parent
}

有简单的方法吗?谢谢你。比如添加标签?

#

Jeff 和 OptimusPrime 的回答都有效。它只允许我选择一个答案。

您必须遍历可视化树,直到找到合适的父级。

DependencyObject depObj = sender as DependencyObject;
while (depObj != null && !(depObj is DataGrid)) {
    depObj = VisualTreeHelper.GetParent (depObj);
}
DataGrid dg = (DataGrid) depObj;

Jeff 的回答应该有效。 既然你提到了 "Tag"。这可能是另一种方式去?虽然可能不是最优雅的方式。

<DataGridTemplateColumn Header="">
<DataGridTemplateColumn.CellTemplate>
        <DataTemplate>    
            <TextBox Text="{Binding FORECAST_MIN, UpdateSourceTrigger=PropertyChanged,NotifyOnTargetUpdated=True}" Tag="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}}" LostFocus="fMin_LostFocus"/>    
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>

并在您的代码中:

private void fMin_LostFocus(object sender, RoutedEventArgs e)
    {
        var tb = (TextBox)sender;
        DataGrid parentDataGrid = (DataGrid)tb.Tag;
    }