如何获取DataGridTextColumn发送者的datagrid父级

时间:2018-07-27 19:31:02

标签: wpf datagrid parent

嗨,我有一个datagrid和下面的代码所示的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事件中,我想从发送者那里获取父datagrid。代码

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

有没有简便的方法?谢谢。像添加标签一样?

Jeff和OptimusPrime的答案均起作用。它只允许我选择一个答案。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

杰夫的答案应该起作用。 由于您提到了“标签”。这可能是另一种方法吗?可能不是最优雅的方式。

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