I have been away for a while exploring the idea of writing a book, for all those of you that left words of encouragement at my blog, thanks a lot. It meant a great deal to me. Unfortunately the publisher turned out to be very narrow minded and could not see the bigger picture or what our book would be like. So the book project is off.
So this article represents the 1st of many of my getting back to my usual article tirade here at codeproject, which is really my true home I feel.
This is a short article but I can promise a very substantial set of articles on what I consider to be my best work, and most useful work to date. The series of upcoming articles will be on a MVVM framework for working with WPF, it actually answers every question/short coming I have ever had with working with WPF and Tests and the MVVM pattern, so stay tuned to that series.
But we are where we are and this is this article, so what does this article actually do. Well it is faily simple we use a lot of ComboBoxes on our UIs to allow users to pick values, and show a selected value, which is great so we have something like
Which works wonderfully providing your data is fairly short and not that complicated. Remember in WinForms and WPF you can put a list of any object you want as a source for a ComboBox so it is not inconceivable that one would have a list of complex classes as an items source. So the above selection/display method just may not cut it, so something more may be required and be useful.
What if we could keep the currently selected item as a simple string, and allow the user to see a
ListView to select the current item from, wouldn't that be nice.
Luckily WPF is so powerful, we can do just that.
Here is what I came up with.
So what we have is the current item is just a short property representation of the entire object that is selected, but when the user wants to make a new selection they get shown the entire object in an appropriate diplay container, in my example I am using a standard (Styled) WPF
ListView, but you could use what ever floats your boat.
So how does all this work, if you want to know please read on.
How It Works
Ok this first thing to understand is what the ComboxBox is being used to select. In this simple demo code (attached) I am using a
ObservableCollection<Person> for the
ComboxBox.ItemsSource, but this could be any
IEnumerable, so something like
List<Person> would do fine as well.
I setup the
ComboBox.ItemSource via a binding on a ViewModel which is used for the DataContext for the demo codes Window. Here is the entire ViewModel code. Though this ViewModel code is really not that important to understand, the only thing you need to get is that the
ComboxBox.ItemsSource is being bound to the ViewModels
People property which is a