Select Page

WPF: GridViewColumnHeader from GridViewColumnThere is no universal way to find GridViewColumnHeader from GridViewColumn that would be convenient and doesn’t impact performance. But in different situations you can choose appropriate method from those described below. They are arranged below in descending order from architectural point of view from more convenient to less one. “From architectural point of view” means: universal for all projects and solutions, convenient for those who will use it, and has minimum impact to performance

GridViewColumnHeader from GridViewColumn – Using Attached Properties

This is the most universal way that have no impact to performance.
The idea is based on GridViewColumnHeader’s knowledge of it’s GridViewColumn via Column property. If we can catch the moment when this Column property is changed we can set some GridViewColumn’s attached property to our GridViewColumnHeader object. Let’s look to code.

With next step we need to bound our synthetic attached property to real Column property.

When the GridViewColumnHeader.Column property is changed, we in BoundGridViewColumnPropertyChanged method set BoundGridViewColumnHeader attached property for Column.
So now we can get GridViewColumnHeader from every GridViewColumn like this:

Using your knowledge about GridViewColumn style

If you sure that your GridViewColumn style always contains GridViewColumnHeader:

than you can get GridViewColumnHeader very easy:

But if the header is set like this

than column.Header will return “My Header” of type string, not GridViewColumnHeader.

Using Visual Tree

You can use this way to find visual children of type GridViewColumnHeader for your GridViewColumn. For example, as here

Next line returns GridViewColumnHeader if it exists or null: