How do i return the column index of an item within a WPF Datagrid, when I click on a cell I'm using Visual Studio 2010/VB.Net
问题:
回答1:
You can use below code directly to get selected cells column index.
int index = datagrid.SelectedCells[0].Column.DisplayIndex;
回答2:
You tried use this at the Event Click for Column Index?
int columnIndex = dataGrid.CurrentColumn.DisplayIndex;
I'm using this code in MouseDoubleClick Event or PreviewKeyUp and works perfectly.
回答3:
DataGridCells
do not have a Click event, they have a Selected
event but that is normally fired for each cell in a row when you click on a cell. GotFocus
might be a better choice.
e.g.
<DataGrid ItemsSource="{Binding Data}">
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<EventSetter Event="GotFocus" Handler="CellClick"/>
</Style>
</DataGrid.CellStyle>
</DataGrid>
and:
void CellClick(object sender, RoutedEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
MessageBox.Show(cell.Column.DisplayIndex.ToString());
}
DataGridCell.Column.DisplayIndex
seems to return an appropriate index, if it somehow is not enough you can use DataGrid.Columns.IndexOf(DataGridCell.Column)
.
回答4:
Every Body Is tells about this solution
Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;
and yes it works but nobody tells that we have to set Display index first fro every column, may be it is quiet obvious for Experts to get that, but for novices it's unfamiliar thing
There are two ways to set it :-
1) You can set it in XAML part..
<DataGridTextColumn Header="Serial No." Width="60" IsReadOnly="True" Binding="{Binding Path=Sno}" DisplayIndex="1"></DataGridTextColumn>
i don't know how to set it for custom columns like
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox x:Name="ChkItem" IsChecked="{Binding Path=Sno}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
so I preferred the other Way
2) Created A function
private void SetDisplayIndexforGridViewColumns()
{
Int32 ColumnCount = dt.Columns.Count;
for (int i = 0; i < ColumnCount; i++)
{
dataGridScannedFiles.Columns[i].DisplayIndex = i;
}
}
dt
is my Data Table
and I am assigning Display Indexes to it
Now if you use
Int32 columnIndex = dataGridScannedFiles.SelectedCells[0].Column.DisplayIndex;
then You will surely Get the Index