我在标题中有一个带CheckBoxes的Datagrid。 单击复选框时,我想知道它的索引列。我在Google上找到的所有内容都是指被点击的单元格,而不是标题项目。尽管我在debuging dep Data DataGridColumnHeader时可以看到,但是while循环不会退出。
Xaml:
<DataGridTemplateColumn>
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<StackPanel Margin="0,-7,0,0" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<CheckBox Margin="0,0,5,0" IsChecked="{Binding DataContext.Day1Cb, RelativeSource={RelativeSource AncestorType={x:Type DataGrid}}}" Click="HeaderCheckBox_Click"></CheckBox>
<TextBlock Text="{x:Static resx:Bla.Day1}"></TextBlock>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding Path=Day1}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
CodeBehind:
private void HeaderCheckBox_Click(object sender, RoutedEventArgs e)
{
DependencyObject dep = (DependencyObject)e.OriginalSource;
while ((dep != null) && !(dep is DataGridColumnHeader))
{
dep = VisualTreeHelper.GetParent(dep);
}
if (dep == null)
return;
if (dep is DataGridColumnHeader)
{
DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
// do something
}
int columnIndex = NavDataGrid.Columns.Single(c => c == dep).DisplayIndex;
}
由于