Thursday, 19 June 2008

WPF: StackPanel vs. Grid

As a new comer to the Microsoft Windows Presentation Framework (WPF), I was perplexed about my ListView. I put a ListView inside a StackPanel, but the ListView does not attempt to occupy the full space of the StackPanel although the Width and Height of the ListView were set to "Auto" - the ListView simply auto-grows based on its contents. When I reduce the size of the window, the ListView does not resize with it either - it just gets clipped. The same thing happens if I put a ScrollViewer into the StackPanel.

Then I found out from some forum (I cannot remember the link now), that when a widget (OK, control, in Microsoft speak) is put in the stack panel, it assumes unlimited canvas space and therefore, does not try to resize. To achieve the effect that I wanted (imaging the ListView of the Windows File Explorer, which occupies the whole space of the window and resizes with the window), I had to replace the StackPanel with Grid. This way, the ListView will auto-resize with its container and shows the scroll-bars accordingly. See screenshot and XAML code snippet below (and yes, I have been using code behind to populate the ListView's GridView column headers programmatically reading from database).

    
        
        
    
    
    
            
                
                    
                
            
    

Although my problem is solved, I cannot help thinking that the behaviour of StackPanel is rather inconsistent - e.g. the GroupBox stretches and resizes with the StackPanel (at least it can anchor itself to the left and right sides), but ListView (or ScrollViewer) cannot.

5 comments:

Romen said...

There is a problem with this posting - it behaves properly in Firefox, but in my IE6 it displays OK, but the page is 'locked up' somehow - i.e. does not respond to mouse clicks on URLs, etc. It is definitely something to do with the XML snippet included in the post - or it could be that IE6 cannot handle it...

Romen said...

I turned out to be wrong - it was because of the #header-wrapper CSS style, which got a negative margin.

Jason said...

Thank you!
I have been banging my head with a ListView nested in a StackPanel where the ScrollViewer would not show. Switching to a Grid fixes it.

Elan Hasson said...
This comment has been removed by the author.
Elan Hasson said...

This definitely helped me with my sizing issue. I had the same nesting as Jason did with the StackPanel contained in a ScrollViewer-- and a Grid resolved the issue!