[英]How to get the DataGridTextColumn sender's datagrid parent
Hi I have a datagrid and the DataGridTextColumn shown in code below: 嗨,我有一个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>
Now in the LostFocus event, I'd like to get the parent datagrid from the sender. 现在在LostFocus事件中,我想从发送者那里获取父datagrid。 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. Jeff和OptimusPrime的答案都起作用。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.