Click here to Skip to main content
11,635,626 members (76,770 online)
Click here to Skip to main content

Please select your collection

, 29 Jun 2009 CPOL 15.5K 15
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>

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="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
	http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>"
  xmlns:x="<a href="http://schemas.microsoft.com/winfx/2006/xaml">
	http://schemas.microsoft.com/winfx/2006/xaml</a>"
  Title="Selection Sample" Height="200" Width="300"
  xmlns:dt="clr-namespace:CompositeTest"
  x:Name="Window">

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>

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.

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

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.

    <ComboBox
      IsEditable="False"
      SelectedIndex="0"
      Margin="20"
      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.

      <ComboBox.SelectedItem>
        <Binding Path="SelectedPerson"
             ElementName="Window"
             Mode="OneWayToSource">
          <Binding.ValidationRules>
            <dt:PersonValidation />
          </Binding.ValidationRules>
        </Binding>
      </ComboBox.SelectedItem>

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.

      <ComboBox.ItemsSource>
        <CompositeCollection>
          <ComboBoxItem>Please select...</ComboBoxItem>
          <CollectionContainer
            x:Name="peopleCollection"
            x:FieldModifier="private"/>
        </CompositeCollection>
      </ComboBox.ItemsSource>
    </ComboBox>

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>

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

Happy coding.

License

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

Share

About the Author

Pete O'Hanlon
CEO
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    Rant Rant    Admin Admin   

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

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