tags:

views:

61

answers:

2

Hi All,

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.

A: 

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?

Goblin
+1  A: 

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.

Ray Burns
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.
Geetha
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 ...>`.
Ray Burns