2

I want to add an item to the combobox after binding it. for example:

this.cbCategory.ItemsSource = categoryList; this.cbCategory.DisplayMemberPath = "CategoryName"; this.cbCategory.SelectedValuePath = "CategoryID"; 

i want to add("All", "%") as the first one.

Geetha.

2 Answers 2

9

This is very simple using a CompositeCollection:

<ComboBox DisplayMemberPath="CategoryName" SelectedValuePath="CategoryID"> <ComboBox.ItemsSource> <CompositeCollection> <my:Item CategoryName="All" CategoryID="%" /> <CollectionContainer Collection="{Binding CategoryList}" /> </CompositeCollection> </ComboBox.ItemsSource> </ComboBox> 

How it works: The CompositeCollection produes the "All" item followed by all of the items in the CategoryList collection. Note that <my:Item ... /> is the constructor for your item class. You will need to change it to your actual namespace and class name.

Important advice: I notice you are setting some ComboBox properties in code-behind. This is a very bad practice. You should use XAML as shown above.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, I am using the class which is present in the other project of the same solution. public class Category { /// <summary> /// Gets or sets the category ID. /// </summary> /// <value>The category ID.</value> public string CategoryID { get; set; } /// <summary> /// Gets or sets the name of the category. /// </summary> /// <value>The name of the category.</value> public string CategoryName { get; set; } } Then how i have to call this.
You can reference any class by setting an appropriate XML namespace. For example, xmlns:otherProject="clr-namespace:NamespaceInOtherProject;assembly=OtherAssembly". Then instead of <my:Item ...> you write <otherProject:Item ...>.
0

You'll break the binding if you try to add it later and will no longer receive updates.

Why not just add your 'extra' item before you bind it?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.