简体   繁体   中英

How to get the DataGridTextColumn sender's datagrid parent

Hi I have a datagrid and the DataGridTextColumn shown in code below:

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

Now in the LostFocus event, I'd like to get the parent datagrid from the sender. Code

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

Is there a easy way to do so? Thank you. Something like adding a Tag?

#

Both Jeff and OptimusPrime's answers work. It only allows me to choose one answer.

You have to traverse the visual tree until you find the proper parent.

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

Jeff's answer should work. Since you mentioned "Tag". This might be another way to go? Probably not the most elegant way though.

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

and in your code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM