05/21/07 EDIT: Fil Fortes was kind enough to point out I’ve put up a non-bindable panel. If you want a good version of this panel you should check out: http://fortes.com/2007/05/07/uniformpanel/
I’m guessing the following scenario hasn’t only happened to me.
You know how a Grid and it’s children will automatically fill all available space?


How many times have you mistakenly attempted to ask StackPanel to do the same thing? For example: I want to have six buttons span the width of my window.


Doh! I’ve done this more times than I’d like to admit.
So your probably thinking to yourself, “So just put them in a Grid and create columns you fool! It’s easy!” And you’re right, that’s what I usually end up doing. But what if you’re dynamically adding/removing objects to your Grid? Then you have to create the rows/columns in code each time a child is added or removed. What a pain! Using a Grid’s Columns/Rows really falls apart if you need this layout to occur in an ItemsControl and your setting the ItemsControl.ItemsPanel property! Now you’re screwed and you’re going to have to write a custom control…like I did.


If you were able to follow the ramblings of that last paragraph then you’ve probably figured how I built SpanningStackPanel. All I did was inherit from Grid and then, depending on Orientation and FlowDirection, I add Columns/Rows when a UIElement is added/removed to the Children collection.
NOTE: I remember Kevin Moore once telling me it’s not worth the overhead of inheriting from anything other than Panel, but in this case I felt it was easier to let Grid do the work it was already programmed to do. This way I didn’t have to mess with any of that ArrangeOverride or MeasureOverride nonsense one usually has when building a custom panel.
There were a couple of things I did to make the panel mimic some of StackPanel’s behavior. Like I mentioned before I have Orientation and FlowDirection properties that control the layout as seen below.



And lastly, to mimic Grid’s behavior I don’t give a control more or less space if it has a hard set Width/Height property. The following screenshot shows the green button with it’s Width property set to 25px.

So that’s it! A panel that acts like a StackPanel while laying out like a Grid.
You can snag the source from here if you want to play around with it.
SpanningStackPanelExample Source
At some point I’ll probably come back to this control and change the way it determines if a control has a set height/width. I don’t like the way I currently implemented it but it works for now. Maybe I’ll come up with a better name then SpanningStackPanel too. SuperUltraliciousMaskedAvengerPanel…that has a nice ring to it.