DataGrid selecting columns to hide - un-hide

Mar 8, 2009 at 12:48 AM
Hi all I have been trying to figure out a way to easily hide or un-hide the columns of a table, e.g. right click on the header column and have a context menu come up for "hide column".  I know that I could probably do this with check boxes somewhere but I did not think that would be as intuitive.  I plan to also give them the option to hide un-hide columns from the menu.

Or how about I put a transparent button over the top of the header text that responds to right clicks only?

Any thoughts?  
Mar 9, 2009 at 2:30 PM
In the control I have been working on that derives from the WPF DataGrid, I have done this (and more) by overriding OnContextMenuOpening(). My version builds the context menu dynamically and thus has access to the up-to-the-millisecond state of the Columns collection, which it uses to populate a submenu offering the user the ability to hide/unhide each of the columns.

Each such menu item is bound to the same Click handler, which simply reverses the visiblity (Collapsed versus Visible). The menu item that the user selected is available in e.OriginalSource, and each MenuItem points to the appropriate DataGridColumn by way of the MenuItem's Tag attribute.

This may or may not be a workable approach for you, but maybe it will give you a starting point.
Mar 9, 2009 at 5:33 PM
Thanks mikj,

This is definitely a great starting place.  It would be nice if there were some built in capabilities like that, similar to an Excel spreadsheet, but I understand that the grid cannot be everything to everyone.

Mar 10, 2009 at 5:23 AM
Okay I did this but when I create the sub menu items in the overridden OnContextMenuOpening() they do not display but if I build them in the OnLoaded event handler for the DataGrid they do show up.  Any thoughts?

Thank you,
Mar 10, 2009 at 5:32 AM
I think I have been coding to long today, I had the visibility set to hidden on the sub menu item. Doh!