V K
V K

Reputation: 1719

How do I get the GridViewColumn Header index in the GridViewColumnHeader.Click event?

I have added a GridView control into my application. Now, I want to find the index of column header that is clicked by user. As I want to check if the column has index 0, and if that is the case then I would remove grouping from the gridview, in other cases I will add grouping into the gridview depending on the column code. Currently I am identifying the column with its header.

But I do not want to hard code the header name. So, I want to know how do I find the index of the column.

Below is the code that I am using in the Header click event handler.

private void ListViewLocalSystem_Click(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
    if (headerClicked != null)
    {
        if (headerClicked.Column.Header.ToString() == "Name")
        {
            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(ListViewLocalSystem.ItemsSource);
            if (view.GroupDescriptions != null)
            {
                view.GroupDescriptions.Clear();
            }
        }
        else if (headerClicked.Column.DisplayMemberBinding is Binding)
        {
            string bindingProperty = ((Binding)(headerClicked.Column.DisplayMemberBinding)).Path.Path;
            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(ListViewLocalSystem.ItemsSource);
            PropertyGroupDescription groupDescription = new PropertyGroupDescription(bindingProperty);
            if (view.GroupDescriptions != null)
            {
                view.GroupDescriptions.Clear();
            }
            view.GroupDescriptions.Add(groupDescription);
        }
    }
}

Upvotes: 0

Views: 1110

Answers (1)

mm8
mm8

Reputation: 169350

You can get the zero-based display index of the column by getting the index of it in the Columns collection of the parent GridViewHeaderRowPresenter:

private void ListViewLocalSystem_Click(object sender, RoutedEventArgs e)
{
    GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;
    if (headerClicked != null)
    {
        GridViewHeaderRowPresenter presenter = headerClicked.Parent as GridViewHeaderRowPresenter;
        if (presenter != null)
        {
            int zeroBasedDisplayIndex = presenter.Columns.IndexOf(headerClicked.Column);
            ...
        }
    }
}

Upvotes: 1

Related Questions