Jul 21 2010

Silverlight/WPF ComboBox with Empty Item allows user to go back to no selection.

Category: mvvm | silverlight | wpfAdministrator @ 23:23

The problem

Imagine a ComboBox bound to some business objects:

<ComboBox ItemsSource="{Binding Items}" SelectedItem="{Binding Item, Mode=TwoWay}">

       

public ObservableCollection<Animal> Items

{

    get { return new ObservableCollection<Animal>(Some animals…)}

}

public Animal Item{get;set;}

 

The state of the ComboBox is initially “no selection”. When the user selects an Item, the SelectedItem is set, but now the user can’t go back to “no selection” because no such item exists in the collection of business objects.

Having to add extra items to the ItemsSource in the ViewModel is a drag. I want to do that in XAML using a generic Converter.

ItemsSource="{Binding Items,Converter={StaticResource AddEmptyItemConverter}}"

 

My initial thought was to just add a Null value to the collection, but this results in a conversion error in the SelectedItem binding when trying to save the single Item back down to the ViewModel. This could be solved with another converter, but I want to do this with just one.

Using only one simple converter

The solution I found was to use dynamics and reflection to instantiate an Object of the correct type and add that to the collection.

    public class AddEmptyItemConverter:IValueConverter

    {

        public object Convert(dynamic value, Type targetType, object parameter, CultureInfo culture)

        {

            if(value!=null)

                if(value.GetType().IsGenericType)

                    if(value.Count>0)

                        value.Insert(0,Activator.CreateInstance(value[0].GetType()));

            return value;

         

        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)

        {

            return value;

        }

    }

 

(You will need to import the CSharp.dll to get the dynamic keyword to work in Silverlight)

If the converter is used on an empty collection, nothing is added. This is great, because in that case the user can’t go away from “no selection” in the first place. (But it’s also reeeally lucky that this is the desired behavior, because I don’t know how I would figure out the type in that case :-) )

This "no selection" will appear as blank in the ComboBox regardless of the ItemTemplate or DisplayMemberPath because all of its properties are Null (or whatever the default constructor of the Business object feels like).

In the ViewModel, the empty object is passed around like a first class citizen and can be bound to other XAML controls. Obviously the logic needs to recognize a “blank” object as a “no selection” if needed.

How to display text in the "empty" Item

If you want some text in the “empty” option, you could use the Converter Parameter to get the converter to inject some text into the object, but that makes the converter less generic and I don’t want the text to get into the object might be pushed back into the ViewModel.

A better solution is to use the fact that we know a property will contain Null. For example the Name property and replace the Null value with some nice string in XAML. In my case, I want to change the Name of the animal in my ItemTemplate to the text "No animal at all!".

<ComboBox.ItemTemplate>
 <DataTemplate
>
  <StackPanel Orientation
="Horizontal">
   <TextBlock Height="25" Text="{Binding Name
}"/>
   <TextBlock Height="25" Foreground="Blue" Text="{Binding Color
}"/>
  </StackPanel
>
 </DataTemplate
>
</ComboBox.ItemTemplate>

 A nice and clean way of doing that (but WPF only) is by giving you textbox a style with a DataTrigger:

<TextBlock Height="25" Text="{Binding Name}">

 <TextBlock.Style>

 <Style TargetType="TextBlock">

  <Style.Triggers>

   <DataTrigger Binding="{Binding Name}" Value="{x:Null}">

    <Setter Property="Text" Value="No animal at all!"/>

   </DataTrigger>

  </Style.Triggers>

 </Style>

</TextBlock.Style>

 </TextBlock>

 

If you are using Silverlight, the datatriggers are not available, but Expression Blends standard “ChangePropertyAction” behavior can be used as an excellent substitute.

Use expression to drag the behavior onto a textbox in the ComboBox’s ItemTemplate and set the properties or import

xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"


and type the interaction trigger in the textbox by hand:

<TextBlock Height="25" Text="{Binding Name}">

 <i:Interaction.Triggers>

  <i:EventTrigger>

    <i:Interaction.Behaviors>

      <ei:ConditionBehavior>

        <ei:ConditionalExpression>

          <ei:ComparisonCondition LeftOperand="{Binding Name}" RightOperand="{x:Null}"/>

         </ei:ConditionalExpression>

       </ei:ConditionBehavior>

      </i:Interaction.Behaviors>

    <ei:ChangePropertyAction PropertyName="Text" Value="No animal at all"/>

  </i:EventTrigger>

</i:Interaction.Triggers>           

 </TextBlock>

 

Tags: , , , , , ,

Comments

1.
Hombianer Hombianer Germany says:

How would you solve the following:
have a combobox with the 'no selection' item, but this has a text like:
a) '(please select an animal)'
b) '(optional: select animal)'

Is there a good generic solution to set the text?
For variant a) there should be also a required field validation.

2.
Erik Erik United States says:

I get compile errors with your code:
Error  1  Predefined type 'Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported  CCCSilverlight
Error  2  One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?  C:\CCCSilverlight\CCCSilverlight\Converters\AddEmptyItemConverter.cs  15  16  CCCSilverlight

something to I think with the first argument in your Convert method being of type "dynamic"

3.
Erik Erik United States says:

I think dynamic typing only exists in WPF, not Silverlight?

4.
Erik Erik United States says:

Scratch that last comment,

Quote:
"One quirk you'll run into, is when using DynamicObject in Silverlight 4 beta, is that you're not having a reference to the assembly were this is located by default, nor is it in the runtime by default. It is in fact located in the SDK. To use the DynamicObject, one needs to add a reference to an assembly called "Microsoft.CSharp.dll", it is located in the Silverlight SDK, typically located here : "C:\Program Files\Microsoft SDKs\Silverlight\v4.0\Libraries\Client"."

From:
silverlightfeeds.com/.../..._in_Silverlight_4.aspx

5.
Tau Sick Tau Sick Denmark says:

Hombianer: Great question! I updated the post with some examples of setting a text in the empty value.

If you want the user to always select an item (required field validation), I don't think you should use this approach at all.

6.
Tau Sick Tau Sick Denmark says:

Thanks Erik, yes - you need the CSharp.dll in Silverlight.

7.
Andrej Tozon Andrej Tozon Slovenia says:

You could also create a default item instance in XAML resources, like  <MyType x:Key="defaultItem" Key="-1" Text="[None]" />
pass that to the converter as a converter parameter, where you simply do value.Insert(0, parameter);
Gives you more control over default property and key without much hassle.

8.
Tau Sick Tau Sick Denmark says:

Andrej - you are brilliant! Very nice alternative, thank's.

9.
Binary Options Binary Options South Africa says:

Hey very nice blog!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds also...

10.
Discount Sofas Discount Sofas United States says:

The blog is a wonderful one. I have found some nice things on the post. I enjoyed the reading and  bookmark the site for further reading. Well done!!!

11.
victorian floral emblem victorian floral emblem United States says:

Nice effort, very informative, this will help me to complete my task.

12.
wow game card wow game card United States says:

I wish I was there!!! Total sad face moment. However, I trust you guys to have made excellent decisions! Great post

13.
website design company website design company United States says:

This is a wonderful information for me. I really impressed by this post. It's very useful and informative. Thanks for sharing.

14.
cruises cruises United States says:

Great read. Do you mind if I reference this in our next newsletter?

15.
flight center flight center United States says:

Solid analysis. Sometimes its hard to see all angles of a topic

16.
apple apple United States says:

Carpet Cleaning - Removal of Pet Dander and Odor in Carpets.....A pet for several people is equal to having an extended member of the family unit.....It can be joyful learning your pet's character and watching them grow.....Regrettably, the price of a pet goes further than the price you paid in the pet store.....

17.
music licensing for film music licensing for film United States says:

The coding shared through this blog post are really awesome. I bookmark the site for further visit as i have found some info. Good work!!!

18.
medigap in nj medigap in nj United States says:

You gave nice ideas here. You made some good points here, I am sure most peoples will agree with your blog. I love this some business objects.

19.
virginia wine virginia wine United States says:

The post on "Silverlight/WPF ComboBox with Empty Item allows user to go back to no selection" is very useful for me, thanks for the sharing.

20.
office furniture office furniture Ireland says:

The coding shared in the post are really excellent and necessary. It is a recommended post for me as I bookmark it for further reading. Nice post. Great job!!!

21.
Female Singer Female Singer United States says:

I was very pleased to find this site. I wanted to thank you for this great read!! This is a very informative post, it helps me more.

22.
property in UAE property in UAE United States says:

Thank so much for sharing great blog nice post and great layout i will add as a favorite for the future.

23.
avidal avidal Romania says:

nice post

24.
emergency dentist emergency dentist United States says:

Awesome post...got blinked with the way you explained..hopefully the writer will be a good speaker too!!!

25.
Flights to Lagos Flights to Lagos United States says:

While reading your blog it seems that you research on this topic very much. I must tell you that your blog is very informative and it helps other also.

26.
Vino Biologico Vino Biologico Italy says:

Your post really helps me to work easily. Thanks for providing such important information.

27.
Preventivo trasloco Preventivo trasloco Italy says:

You made some good points there. I did a search on the topic and found most people will agree with your blog. Thanks

28.
internet televsion software  internet televsion software United States says:

I definitely wanted to compose a simple remark to thank you for all the awesome tips and tricks you are writing at this website. My rather long internet lookup has at the end been rewarded with awesome tips to write about with my contacts. I 'd suppose that most of us visitors are rather fortunate to dwell in a great website with so many lovely professionals with insightful advice. I feel somewhat blessed to have encountered your entire website and look forward to plenty of more fabulous times reading here. Thank you once more for a lot of things.

29.
watch tv on the internet  watch tv on the internet United States says:


I would like to convey my gratitude for your kindness for those people who should have help with the theme. Your personal dedication to getting the solution along has been extremely valuable and has always made most people like me to get to their aims. Your own warm and friendly key points entails this much a person like me and far more to my office workers. Regards; from each one of us.

30.
Capodanno roma Capodanno roma Italy says:

Hi, The topic that you have discussed in the post is really amazing, I think now I have a strong hold over the topic after going through the post. I will surely come back for more information.

31.
Jordans for Cheap Jordans for Cheap People's Republic of China says:

Good post. I like it very much. thank you! <a href="http://www.nikejordans.net/"> Jordans for Cheap</a>

32.
chicago web design chicago web design United States says:

I didn't know this function until I have read your post, thanks a lot for sharing this to us. I appreciate it a lot!

33.
Cheap Dumbbells Cheap Dumbbells United States says:

Many of the user comments on this article are simply terrible. Do noone read the entire article these days?

34.
satellite tv channels  satellite tv channels United States says:

I was plannig to clear my hassle   touched to this site and I would say that I am bright enough that I   got across to your website and today   I got atleast a clew, how to   run ahead . I am   very appreciating your  nice work and your writing on this site. I  sometimes use  google to finidng for my matter   and I saw your site on top page. Keep up the   important work go on.

35.
acheter sildenafil acheter sildenafil United States says:

This post was very nicely written, and it also contains a lot of useful facts. I appreciated your distinguished way of writing the post.Thank you!

36.
send flowers in dubai send flowers in dubai United States says:

Thanks for share this excellent information with us i’ll never forget this type of information and tells others about it! Thanks once again

37.
Florence Luxury Apartments Florence Luxury Apartments United States says:

Hi, I appreciate the information that you have provided in the post. It is worth noting and I really liked the presentation as well. I will surely come back for more of interesting posts.

38.
watch tv on the internet watch tv on the internet United States says:

Thanks for share this excellent information with us i’ll never forget this type of information and tells others about it! Thanks once again

39.
maui villa maui villa United States says:

Nice position thanks for a sharing this position.

40.
adult sex adult sex United States says:

Pretty gracious displace. I retributory stumbled upon your blog and desirable to say that I change really enjoyed datum your blog posts. Any way I'll be subscribing to your have and I wish you station again shortly.

41.
replica sunglasses replica sunglasses United States says:

This is an interesting post. I like the code that you have shared. Thanks for sharing and keep up the good work.

42.
Rec to Rec Singapore Rec to Rec Singapore United States says:

This website provides such a valuable information. Thanks

43.
William J. Hughes Te William J. Hughes Te United States says:

Your site is very good. There are useful information and most importantly, for sharing great. you have posted.

44.
Ladies worker boots Ladies worker boots United States says:

Such a very  valuable information. Thanks for this excellent read.

45.
motorbike clothing motorbike clothing United States says:

Such a very  valuable information. Thanks for this excellent read.

46.
Inspection in china Inspection in china United States says:

Such a nice post. It gives us many informative things. Dont stop blogging. Keep it up.

47.
wholesale swarovski jewelry wholesale swarovski jewelry People's Republic of China says:

Hello, thanks for you give me so good post,this article give me many new ideas, make me achieve a breakthrough.
http://www.myjewelrybox.org/Bangles_1_1.htm
http://www.myjewelrybox.org/Bangles_1_2.htm

48.
tiffany sterling silver tiffany sterling silver United States says:

While reading your blog it seems that you research on this topic very much. I must tell you that your blog is very informative and it helps other also.

49.
Boots Wholesale Boots Wholesale United Kingdom says:

Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon.

50.
mical mical United States says:

Grandfather, Great Spirit, once more behold me on earth and lean to hear my feeble voice.We all act upoun
curt

51.
San Francisco Roofing San Francisco Roofing United States says:

Thanks for this awesome piece.  I liked it a lot! Smile
So, thx for this!
Thanks for writing Smile
This was cool.
This was cool to read, thanks.
I truly enjoyed your post.
thank you for thinking about this and writing it
thanks a bunch for writing this post, I enjoyed the read.
You have a cool view Smile
I like what you wrote
Thx for putting this out there
1 of the most awesome aspects about the blog society is all the stuff people freely give.  Thanks! ;)
Good post!
thank you!
Came across your site through StumbleUpon Smile
Found your blog marked on Reddit
I'll Digg this, thanks!
Really enjoyed the post.
I really enjoyed reading your post
Excellent read, thanks for putting it up.
Interesting Post
Nice post, I can't wait for more
Enjoy your writing
I enjoyed your post
Your website is nice
Awesome, thanks a million for posting this!
Just wanted to say tHANKS for this
Hi there, just want to drop a note and say cool post!
Thank you for writing this.  It's sometimes a struggle to keep up with my blogging.  Seeing a site that has such a great personality is very inspirational.
Thanks a bunch for this, I like your blog.  Long time reader, first time commenter, you know the drill.  I attempted to post this one time before, I don't believe it went through...with any luck it will this time! Laughing

53.
buy Dubai property buy Dubai property United States says:

Spot on with this article, I really think this website needs more attention.  I'll probably be back to read more, thanks for the info.

54.
apartment for rent Dubai apartment for rent Dubai United States says:

I have to say this has been probably the most helpful posts for me. Please keep it up. I cant wait to read whats next.

55.
professionele website professionele website United States says:

This is a nice post about Silverlight. Even I like the code that you have shared. Thanks for sharing and keep up the good work.

57.
email campaign management email campaign management United States says:

YTPL houses a capable and result oriented team of professionals and managers who can assist you with
a wide range of solutions ranging from ERP implementations to email campaign management .

58.
Events Company Events Company United States says:

Information and attractive sentences on this blog will surely entice sense as Blogger this blog published information after making lots of research so that people can get only reliable and useful information.www.accolade-corporate-events.com/...tainment.html

60.
hesi practice questions hesi practice questions United States says:

I found this page while searching over Google and it seemed to be very interesting for me (especially in concern with this particular topic) .Thanks for sharing this post.

61.
VigRx plus VigRx plus United States says:

If easy and readable sentences and authentic information is combined together, then blog will certainly amazed you. And this blog has everything including useful information and clear sentences that help reader in understanding and getting information easily. http://www.buycheapenhancementpills.com

62.
FiveFingers FiveFingers says:

Vielen Dank für den Austausch dieses Wissens. Hervorragend geschrieben Artikel, wenn nur alle Blogger angeboten das gleiche Gehalt wie Sie wäre das Internet ist ein viel besserer Ort.

63.
chanel messenger bags chanel messenger bags People's Republic of China says:

Ich mag dieses Artikels, sind besonders gut.

64.
links of london links of london People's Republic of China says:

Ich mag dieses Artikels, sind besonders gut.

65.
email campaign management email campaign management United States says:

This is a great blog posting and very useful. I really appreciate the research you put into it.

66.
Dubai apartments rent Dubai apartments rent U.A.E. says:

Its really useful Post. I will go through it. Thank you for the nice Post.