How to toggle a WPF Grid column visibility

serialhobbyist picture serialhobbyist · Aug 2, 2009 · Viewed 23.4k times · Source

I'm having some trouble getting this to work in a WPF app I'm working on. Basically, what I'm after is something like the Task pane in an MMC:

  • The app has three columns in the main part of the display. I need a column on the right side which is resizable. I presume this means using a Grid with a GridSplitter but anything that works will do.
  • I want to be able to save the width of the right-side column when the app is closed and load it when the app is opened but this should be an initial size: the user should be able to resize it.
  • When I resize the window, I want the left- and right-side columns to stay the same size and the middle column to resize with the window width.
  • The left- and right-side columns need to have a minimum width. When I resize the right-side column I want the centre column to get smaller but not the left-side column.
  • I also want to be able to toggle the visibility of the right-side column with a toggle button which is outside the column and when it returns to visibility I want it to be the same width it was before.

I'm trying to do as much as possible in XAML and with binding.

And can I have it topped with cream, ice cream and chocolate chips, please? :-)

Answer

Joel B Fant picture Joel B Fant · Aug 12, 2009

As I read your requirements, instead of thinking of a Grid, I think of a DockPanel.

<DockPanel>
    <Grid Name="right"
        DockPanel.Dock="Right" MinWidth="100" />
    <Grid Name="Left"
        DockPanel.Dock="Left" MinWidth="100" />
    <Grid Name="middle" />
</DockPanel>

If you make a way to resize right, then middle will change as right is resized. If you resize the window, only middle will change. Storing and setting the Width of right is up to you, but shouldn't be hard.

As for allowing the user to resize right, that will a bit trickier, but I found this article that should help. This other article might help even more.

For the visibility of right, you can set its Visibility to Collapsed to hide it and restore it by setting it to Visible.

Note: The panels inside don't have to be Grids, but you will want to use some sort of Panel for each. Whatever you have inside your current Grid columns should work just fine.