Get GridViewColumn Header value from ListView?

12.3k views Asked by At

I have this XAML code

<ListView Name="_lvContacts" ItemsSource="{Binding AccountPhonesList}"
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="{Binding Path=ColumnHeader1}" DisplayMemberBinding="{Binding Path=Home}" Width="70" />
                        <GridViewColumn Header="{Binding Path=ColumnHeader2}" DisplayMemberBinding="{Binding Path=Office}" Width="70" />
                        <GridViewColumn Header="{Binding Path=ColumnHeader3}" DisplayMemberBinding="{Binding Path=Mobile}" Width="70" />
                        <GridViewColumn Header="{Binding Path=ColumnHeader4}" DisplayMemberBinding="{Binding Path=Other}" Width="70" />
                        <GridViewColumn Header="{Binding Path=ColumnHeader5}" DisplayMemberBinding="{Binding Path=Email}" Width="70" />
                    </GridView>
                </ListView.View>
            </ListView>

And this is code behind

            for (int i = 0; i < _lvContacts.Items.Count; i++)
            {
                string header = _lvContacts.Items[i].ToString();
                MyFunction(header);
            }

How can I get the GridViewColumn Header from ListView?I was trying to get GridView from ItemSources but this is already used by collection!I dont know what else I can say about this.

I hope this is understandable.

4

There are 4 answers

1
Nitin On BEST ANSWER

In your case you can do:

((GridView)_lvContacts.View).Columns[i].Header
1
Vlad On

You can get GridView, and the columns in the following way:

GridView gridView = (GridView)_lvContacts.View;
foreach(GridViewColumn column in gridView.Columns)
    // do something with column.Header. Your example:
    if (ItsTheColumnHeaderIWant(column.Header))
    {
        MyFunction(column.Header);
    }

Or, you can name the GridView in your xaml:

<GridView x:Name="_gridView"...>

And then you can just directly access it from code: _gridView.Columns.

0
Andrew On

To get all of the headers, you can use the following code:

List<GridViewColumnHeader> headers = GetVisualChildren<GridViewColumnHeader>(_lvContacts).ToList();

public static IEnumerable<T> GetVisualChildren<T>(DependencyObject parent) where T : DependencyObject
    {
        int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < childrenCount; i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child is T)
                yield return (T)child;

            foreach (var descendant in GetVisualChildren<T>(child))
                yield return descendant;
        }
    }
0
Latency On

Use LINQ!!!

  var headers = ((GridView) _lvContacts.View).Columns.ToDictionary(column => column.Header.ToString());