I am trying to implement a ListView with a GridView with sortable columns. To sort the ListView I hook up the Click event for the GridViewColumnHeaders and adding SortDescriptors to the default view source (similar to what is done in MSDN).
Something like this:
<ListView ItemsSource="MY ITEMS SOURCE BINDING">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn DisplayMemberBinding="MY DISPLAYMEMBER BINDING">
<GridViewColumnHeader Content="My Header" Click="ColumnHeaderClicked"/>
This all works fine, but I would like to generalize it a bit. To do that I simply derived GridViewColumnHeader and wrote a click-handler. I know there are many sortable list view implementations out there typically deriving from ListView, but I was just wondering if this approach is possible.
Something like this:
<ListView ItemsSource="MY ITEMS SOURCE BINDING">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn DisplayMemberBinding="MY DISPLAYMEMBER BINDING">
<local:SortableGridViewColumnHeader Content="My Header"/>
For this to work I need to navigate from the SortableGridViewColumnHeader code to the containing ListView in order to set new SortDescriptors.
I tried navigating up the Parent ladder, but the GridViewColumnHeader is not a visual child of my ListView. Surely I could make a dependency property and bind it to the ListView, but there must be a way to navigate to it instead.
How would I do that in code? (I am not looking for answers on how to sort a WPF ListViews in general, I am wondering if it can be done this way).
EDIT
It turned out that what I needed was this parent searcher in the click-handler of my GridViewColumnHeader derivative.
DependencyObject parent = this;
do
{
parent = VisualTreeHelper.GetParent(parent);
if (parent == null) return;
} while (!(parent is ListView));
Now my sorting works like a charm.