The Variable Container

The situation -- you have a listbox that you'd like to populate with a bunch of fairly similar, but not quite the same, items.  Some of the data is contained in a little textbox, some in a larger one, some in a combobox, or perhaps some things are just checkboxes.  You'd prefer not to create any part of the control in code, as you'd like it to look nice (it can be done, but I'm always more confident of how something looks when I design it in Blend). 

One nice way to get this to work (with suggestions from Dante - https://blogs.msdn.com/danteg) is to play games with the Visibility of an object.  Create a new UserControl and make its LayoutRoot a StackPanel with a horizontal Orientation.  Add a label as the first item in the StackPanel.  Then add all of the types of containers you want - textboxes of various sizes, comboboxes, even image containers if you are so inclined. 

Going into the code-behind file, add an enum and a new constructor that takes an argument of that very same type of enum.  Be sure not to delete the default constructor or Blend won't be able to instantiate the object (unless you don't care if Blend is ever able to instantiate it).  This VariableDataContainer, as I have so cleverly labeled mine, is an item added to a ListBox.  When I create the containers, I do so and tell the container what kind of data it will be holding via the enum in the constructor.  The constructor then sets the visibilities of all the inappropriate containers to Visibility.Collapsed, and the right one to Visibility.Visible (this is an Avalon enum).  Ta-da... it now looks like your ListBox is containing various different kinds of objects.

Of course this has the downside of instantiating unnecessary textboxes, comboboxes, and the like, but if you keep the number of containers to a minimum this shouldn't be a horrendous problem.  If your app lags because you are making 5n objects instead of n... your app is a rare bird indeed.  Or just a really powerful one.  Anyhow, my application is not keeping data on every resident of New York, so it works just fine.  Well, the data container works just fine; the app is still under development.

Update: 3/9/08 -- a reader requested the source code for this container, and I have posted a link to it below.  Please bear in mind that the code is not up to production level yet (though it isn't for a Microsoft product anyway), and there are certainly areas that could stand to be improved.

VariableContainer.cs