(WPF Datagrid) How do I determine the Column Index

2019-04-27 01:00发布

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

4条回答
We Are One
2楼-- · 2019-04-27 01:24

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

查看更多
淡お忘
3楼-- · 2019-04-27 01:38

You can use below code directly to get selected cells column index.

int index = datagrid.SelectedCells[0].Column.DisplayIndex;
查看更多
叛逆
4楼-- · 2019-04-27 01:43

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

查看更多
Animai°情兽
5楼-- · 2019-04-27 01:44

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.

查看更多
登录 后发表回答