当我点击WPF Datagrid中的单元格时,如何返回该项的列索引?我正在使用Visual Studio 2010/VB.Net。
当我点击WPF Datagrid中的单元格时,如何返回该项的列索引?我正在使用Visual Studio 2010/VB.Net。
int columnIndex = dataGrid.CurrentColumn.DisplayIndex;
int index = datagrid.SelectedCells[0].Column.DisplayIndex;
大家都在谈论这个解决方案
Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;
是的,它有效,但没有人告诉我们必须为每列设置显示索引,这对于专家来说可能很明显,但对于新手来说,这是一个陌生的事情。
有两种方法可以设置它:
您可以在XAML部分中设置它。
我不知道如何为自定义列设置它。
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="ChkItem" IsChecked="{Binding Path=Sno}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
Created A function
private void SetDisplayIndexforGridViewColumns() { Int32 ColumnCount = dt.Columns.Count;
for (int i = 0; i < ColumnCount; i++)
{
dataGridScannedFiles.Columns[i].DisplayIndex = i;
}
}
dt
是我的数据表,我正在为它分配显示索引。
现在,如果您使用以下代码:
Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;
DataGridCells
没有 Click 事件,它们有一个 Selected
事件,但通常在单击单元格时会为该行中的每个单元格触发。 GotFocus
可能是更好的选择。
例如:
<DataGrid ItemsSource="{Binding Data}">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="GotFocus" Handler="CellClick"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
并且:
void CellClick(object sender, RoutedEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
MessageBox.Show(cell.Column.DisplayIndex.ToString());
}
DataGridCell.Column.DisplayIndex
似乎返回了一个合适的索引,如果不够用,你可以使用 DataGrid.Columns.IndexOf(DataGridCell.Column)
。
从DataGrid(在WPF中使用LINQ)获取特定列名的列索引
int index = DataGrid.Columns.Single(c => c.Header.ToString() == "Department").DisplayIndex;