Click here to Skip to main content
12,942,930 members (42,297 online)
Click here to Skip to main content
Add your own
alternative version


15 bookmarked
Posted 21 May 2009

Please select your collection

, 29 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
In this post, I'd like to cover a fairly common scenario that I've received various bits of email about as WPF is becoming more and more popular with developers.

In this post, I'd like to cover a fairly common scenario that I've received various bits of email about as WPF is becoming more and more popular with developers. A common requirement for a lot of developers is to have a ComboBox contain an entry at the top of the list prompting the user to select an item from the list. As the list is normally populated using a collection of some description, it would seem at first glance, that the only way to actually put a selection choice in is to actually modify the list somehow – and this is precisely the advice that several “professional developers” offer.

You can probably guess by the tone of the end of that previous paragraph that I don't agree with this approach. It just smacks way too much of a hack to my liking. Rejoice though, WPF provides a neat way to get round this problem, and I'm going to demonstrate a limitation of one of the classes we use to get round the limitation.

Right, let’s start off by defining the class that we are going to display in the ComboBox. It’s a variation of our old faithful, the Person class.

namespace CompositeTest
  using System;
  using System.ComponentModel;

  /// <span class="code-SummaryComment"><summary>
</span>  /// This class defines the person.
  /// <span class="code-SummaryComment"></summary>
</span>  public class Person : INotifyPropertyChanged
    private string _name;
    /// <span class="code-SummaryComment"><summary>
</span>    /// The name of the person.
    /// <span class="code-SummaryComment"></summary>
</span>    public string Name
        return _name;
        if (_name != value)
          _name = value;

    /// <span class="code-SummaryComment"><summary>
</span>    /// Raise change notifications.
    /// <span class="code-SummaryComment"></summary>
</span>    ///
<param name="property">The property to raise the
    /// notification on.<span class="code-SummaryComment"></param>
</span>    protected virtual void OnChange(string property)
      PropertyChangedEventHandler handler = propertyChanged;
      if (handler != null)
        handler(null, new PropertyChangedEventArgs(property));
    #region INotifyPropertyChanged Members

    private event PropertyChangedEventHandler propertyChanged;
    public event PropertyChangedEventHandler PropertyChanged
      add { propertyChanged += value; }
      remove { propertyChanged -= value; }


As you can see, it’s a bog-standard POCO implementation, with no “goo” in place to handle a “magic” item.

Next, we define the XAML that we are going to use. Don't worry about the complexity at the moment, as we'll soon break it down to better understand what’s going on.

<Window x:Class="CompositeTest.Window1"

  xmlns="<a href=""></a>"
  xmlns:x="<a href=""></a>"
  Title="Selection Sample" Height="200" Width="300"

Obviously we want to put something in place to inform the user that they need to select a person from the list. A good way to do this is to put a validation rule into place, and that’s what we are going to do. Here’s the code:

namespace CompositeTest
  using System;
  using System.Windows.Controls;
  using System.Globalization;
  /// <span class="code-SummaryComment"><summary>
</span>  /// Validate the ComboBox to see whether or not the
  /// user has chosen a person.
  /// <span class="code-SummaryComment"></summary>
</span>  public class PersonValidation : ValidationRule
    /// <span class="code-SummaryComment"><summary>
</span>    /// Validate the item to see if it's a ComboBoxItem or not.
    /// If it is a ComboBoxItem, this means that the user has
    /// chosen the please select item.
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><returns>A ValidationResult based on the test</returns>
</span>    public override ValidationResult Validate(object value,
      CultureInfo cultureInfo)
      if (value is ComboBoxItem)
        return new ValidationResult(false,
          "Selection is invalid");
      return new ValidationResult(true, null);

The validation logic is fairly simple. If the value is a ComboBoxItem, this means the user has chosen the Please select… option from the list. Any other selection means the user has chosen a Person from the list.

Now, let’s break the XAML down a little bit.

  <DataTemplate x:Key="PersonTemplate">
      <TextBlock Text="{Binding Path=Name}" />
  <ControlTemplate x:Key="ValidationTemplate">
      <AdornedElementPlaceholder />
      <TextBlock Foreground="Red"
             ToolTip="You must choose an item">*</TextBlock>

Here we've created a data template that we are going to apply to the combo box, and a control template that will be applied when there are validation failures. The use of AdornedElementPlaceHolder is an easy way to place a decorated control relative to other items in your template.

  ItemTemplate="{StaticResource PersonTemplate}"
  Validation.ErrorTemplate="{StaticResource ValidationTemplate}"

Here we're hooking the item template to the data template, and the error template to the control template we talked about above.

  <Binding Path="SelectedPerson"
      <dt:PersonValidation />

Whenever the selected item changes, the application is going to perform the validation that we defined in the PersonValidation class. If there’s a failure, the application will apply the validation template.

      <ComboBoxItem>Please select...</ComboBoxItem>

We finally get to the magic. Where you may be tempted, in normal use, to just set the ItemsSource to a standard Binding, we need to use a CompositeCollection instead. This handy class allows us to put pretty much any type of data into the ItemsSource (within reason). To use it, we add a ComboBoxItem to the CompositeCollection that displays the text we want to appear at the top of the combo box.

Next, we add a collection to the CompositeCollection using a CollectionContainer. In most of the samples you see of this on the web, it binds to a StaticResource and is perfectly happy. If you want to bind to a DataContext, however, you're kind of stuffed – the CompositeCollection is not Freezable and, in order to bind to the data context, you have to have a chain of Freezable items. So, if you can't do <CollectionContainer Collection=”{Binding}” /> in your XAML, what can you do?

Well, the answer is to do it in the code behind. All you need to do is set the Collection as in the following class (you need to expose the CollectionContainer to your code behind, hence the use of x:Name on it):

namespace CompositeTest
  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Windows;
  using System.Windows.Controls;
  using System.Windows.Data;
  using System.Windows.Documents;
  using System.Windows.Input;
  using System.Windows.Media;
  using System.Windows.Media.Imaging;
  using System.Windows.Navigation;
  using System.Windows.Shapes;
  using System.Collections.Specialized;
  /// <span class="code-SummaryComment"><summary>
</span>  /// Interaction logic for Window1.xaml
  /// <span class="code-SummaryComment"></summary>
</span>  public partial class Window1 : Window
    private List<Person> list = new List<Person>();
    public Window1()


    private void BindData()
      list.Add(new Person { Name = "Peter" });
      list.Add(new Person { Name = "Karl" });
      list.Add(new Person { Name = "Sacha" });
      list.Add(new Person { Name = "Bill" });
      list.Add(new Person { Name = "Josh" });

      peopleCollection.Collection = list;

Armed with this information, you can now provide Please select functionality in your applications without any real problems.

Happy coding.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Pete O'Hanlon
United Kingdom United Kingdom
A developer for over 30 years, I've been lucky enough to write articles and applications for Code Project as well as the Intel Ultimate Coder - Going Perceptual challenge. I live in the North East of England with 2 wonderful daughters and a wonderful wife.

I am not the Stig, but I do wish I had Lotus Tuned Suspension.

You may also be interested in...

Comments and Discussions

GeneralCool stuff O'Hanlon Pin
Sacha Barber23-May-09 1:25
mvpSacha Barber23-May-09 1:25 
GeneralRe: Cool stuff O'Hanlon Pin
Pete O'Hanlon23-May-09 5:27
mvpPete O'Hanlon23-May-09 5:27 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170518.1 | Last Updated 29 Jun 2009
Article Copyright 2009 by Pete O'Hanlon
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid